NumberFormatting exception for bigint - java

I am using database as postgresql, connecting to the database with spring jdbctemplate.
The phone column in database is phone bigint The spring is throwing the java.lang.NumberFormatException
public UserDetails getUserDetails(int phone) {
String sql = "SELECT * FROM users where phone = ?";
UserDetails users = (UserDetails) jdbcTemplate.query(sql,new Object[]{phone},
new BeanPropertyRowMapper<UserDetails>(UserDetails.class));
return users;
}
**Error:-**
> For input string: "7894561230"; nested exception is
> java.lang.NumberFormatException: For input string: "7894561230"
My Bean is :-
public class UserDetails {
private int userId;
private String name;
private String email;
private String phone;
}

You problem is with int.
In Java int can hold any whole number from -2147483648 to 2147483647 and your value 7894561230 is out of range for it. So use long in place of int.

Related

ERROR: duplicate key value violates unique constraint "user_username_key" Detail: Key (username)=(test) already exists

I have a problem trying to delete, then save a user in an application using the PostgreSQL database. Here is my controller:
#PostMapping
public String addCalories(#RequestParam Integer consumedKcal, HttpServletRequest request){
User u = (User) request.getSession().getAttribute("u");
User newUser = this.userService.save(u.getUsername(), u.getPassword(), u.getAge(), u.getGender(), u.getHeight(), u.getWeight(), u.getGoal(), u.getActivity_rate(), u.getKcal_needed(), u.getBmi(), consumedKcal);
return "redirect:/home";
}
Here is my service method:
#Override
#Transactional
public User save(String username, String password, Integer age, String gender, Float height, Float weight, String goal, String activity_rate, Integer kcal_needed, Float bmi, Integer kcal_consumed) {
this.userRepository.deleteUserByUsername(username);
User u = new User(username, password, age, gender, height, weight, goal, activity_rate, kcal_needed, bmi, kcal_consumed);
return this.userRepository.save(u);
}
The repository:
public interface UserRepository extends JpaRepository<User, Integer> {
User findUserByUsername(String username);
void deleteUserByUsername(String username);
}
The entity:
#Data
#Entity
#Table(name = "user_app")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer username_id;
private String username;
private String password;
private Integer age;
private String gender;
private Float height;
private Float weight;
private String goal;
private String activity_rate;
private Integer kcal_needed;
private Float bmi;
private Integer kcal_consumed;
private Integer water_consumed;
}
The JPA method delete works fine, it deletes the user. But I get this error duplicate key value violates unique constraint "user_username_key" Detail: Key (username)=(test) already exists. I don't know how to solve it. Any help is welcome.

mybatis "Select * from Table" return list of numbers instead of list of objects

I'm having a problem where when I use mybatis Mappers to get and Object from my h2 database I end up getting an array of subsequent numbers instead of an array mapped to the Class of objects I inserted into the database. For instance, if I insert 3 messages into the Message table I get [1,2,3] when I query the database instead of a List containing my messages. Here is my code:
Schema:
CREATE TABLE IF NOT EXISTS MESSAGES (
messageid INT PRIMARY KEY auto_increment,
username VARCHAR NOT NULL,
messageText VARCHAR NOT NULL,
createdTime DATETIME NOT NULL
);
Model:
public class Message {
private String username;
private String messageText;
private Integer messageid;
private Date createdTime;
public Message(String username, String messageText, Integer messageid, Date createdTime) {
this.username = username;
this.messageText = messageText;
this.messageid = messageid;
this.createdTime = createdTime;
}
// Getters and Setters
}
Mapper
#Mapper
public interface MessageMapper {
#Select("SELECT * from MESSAGES ORDER BY createdTime")
List<Message> getAllMessages();
#Select("SELECT * from MESSAGES WHERE username = #{username}")
Message getMessage(String username);
#Insert("INSERT INTO MESSAGES (username, messageText, createdTime) VALUES(#{username}, #{messageText}, #{createdTime})")
#Options(useGeneratedKeys = true, keyProperty = "messageid")
int insert(Message message);
}
Message Service
#Service
public class MessageService {
private MessageMapper messageMapper;
public MessageService(MessageMapper messageMapper) {
this.messageMapper = messageMapper;
}
public int createChatMessage(Message message) {
Message newMessage = new Message(message.getUsername(), message.getMessageText(), null, new Date());
return messageMapper.insert(newMessage);
}
public List<Message> getAllMessages() {
return messageMapper.getAllMessages();
}
public Object getMessage(String username) { return messageMapper.getMessage(username); }
}
And Message Controller
public class MessageController {
private MessageService messageService;
public MessageController(MessageService messageService) {
this.messageService = messageService;
}
#GetMapping("/chat")
public String getChats(#ModelAttribute("message") Message message, Authentication authentication, Model model) {
model.addAttribute("messages", this.messageService.getAllMessages());
model.addAttribute("username", authentication.getName());
return "chat";
}
#PostMapping("/chat")
public String postChat(#ModelAttribute("message") Message message, Authentication authentication, Model model) {
String username = authentication.getName();
message.setUsername(username);
message.setCreatedTime(new Date());
messageService.createChatMessage(message);
message.setMessageText("");
model.addAttribute("messages", this.messageService.getAllMessages());
model.addAttribute("username", username);
return "chat";
}
}
I can see in my h2 console that when I add messages they are correctly inserted into the database but when I try and use the method messageService.getAllMessages() in the MessageController it throws the error:
Data conversion error converting "I wanna dance" [22018-200]; nested exception is org.h2.jdbc.JdbcSQLDataException: Data conversion error converting "I wanna dance" [22018-200]] with root cause
java.lang.NumberFormatException: For input string: "I wanna dance"
Again, if I add 3 messages System.out.println(messageService.getAllMessages()) prints [1,2,3]
Can anybody tell me what mistake I am making?
Your problem is probably the order of columns.
When you query for SELECT * from MESSAGES you don't define the columns. So you will get the columns as defined in your create-table:
messageid
username
messageText
createdTime
But your Message class defines the properties in the following order:
username
messageText
messageid
createdTime
The error message you get looks like it can't convert something to an int field, probably the third column messageText to messageid.
I would try to add the columns in the correct order to your select clause. Like SELECT username, messageText,messageid,createdTime from MESSAGES
If that doesn't help I would start with selecting just a single column and building up from there.
About the printing of "1,2,3" - how does your toString() Method look like in the Message class? Because that's what will get printed, if you print a List.

How to save token in database

I have a class User with:
int id;
String username;
String password;
String token;
Date tokenExpires;
And i have a method like this:
private EntityManager em;
private User authenticate(String username, String password) throws Exception {
// Authenticate against a database, LDAP, file or whatever
// Throw an Exception if the credentials are invalid
Query query = em.createQuery("Select u from User u WHERE u.username = :name and u.password = :password");
query.setParameter("name", username);
query.setParameter("password", password);
return (User) query.getSingleResult();
}
and a method to generate a token:
private String issueToken(String username) {
Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);
return token;
}
how to save this token to db, everytime user log in? so when user log in should generate a token, if user log in again it should generate a new token
When a user logs in, simply fetch the user from the database, then set the mentioned fields, the token and its' expiration date:
public User updateUser(String username, String password) {
User user = getUserBy(username, password);
String token = issueToken();
// token expires in 30 mins;
Date tokenExpires = new Date(System.currentTimeMillis() + 1800000);
user.setToken(token);
user.setTokenExpires(tokenExpires);
entityManager.getTransaction().begin();
entityManager.merge(user);
entityManager.getTransaction().commit();
}
Considering you are using Hibernate, then, the User model has to be annotated as well:
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private String token;
#Temporal(TemporalType.TIMESTAMP)
private Date tokenExpires;
// getters and setters, make sure they are present
}
if you use spring, try this guide, for example: https://javadeveloperzone.com/spring-boot/spring-boot-oauth2-jdbc-token-store-example/

Jdbc returns empty list but SQL query succesfully gets data [Spring]

I am trying to execute this query:
#Override
public UserInfo get(Long id) {
String sql = "SELECT * FROM users WHERE id = ? ";
List<UserInfo> list = jdbcTemplate.query(sql,new UserInfoMapper(),id);
return list.get(0);
}
but jdbc return empty list and I get exception at return line.
But if try to execute directly though the console it returns:
Query, Answer
Query was executed with id 1 and retured correct anwser;
But in method its returned this
I couldn't find any same questions so that may be point at my inattention to something. But I can't see any problem that may cause this. Thanks in advance;
Updated 1
Changing code to
#Override
public UserInfo get(Long id) {
String sql = "SELECT * FROM users WHERE id = ? ";
List<UserInfo> list = jdbcTemplate.query(sql, new Object[] {id},new UserInfoMapper());
return list.get(0);
}
resulted in same: result
Updated 2
#Override
public UserInfo mapRow(ResultSet resultSet, int i) throws SQLException {
UserInfo info = new UserInfo();
info.setId(resultSet.getLong("id"));
info.setFirstname(resultSet.getString("firstname"));
info.setMiddlename(resultSet.getString("middlename"));
info.setLastname(resultSet.getString("lastname"));
info.setUsername(resultSet.getString("username"));
info.setPassword(resultSet.getString("password"));
info.setEmail(resultSet.getString("email"));
info.setMobilephone(resultSet.getString("mobilephone"));
info.setPosition(resultSet.getString("position"));
return info;
}
public class UserInfo {
private Long id;
private String firstname;
private String middlename;
private String lastname;
private String username;
private String password;
private String email;
private String mobilephone;
private String position;
public UserInfo() {
}
}
Getter and setters for each field is there but I think there is no need to show them up.
Check user credentials that you are using to connect database from your application and the user credentials in console. And also check owner schema , table owner schema in your application.

Using Sugar ORM with UUID or Joda-Time

I'm creating a mobile application that will have users as defined below:
public class UserObject extends SugarRecord<UserObject>
{
public UUID Id;
public String Name;
public int DefaultSort;
public String Username;
public Date LastLogin;
public UserObject()
{
}
public UserObject(UUID id, String name, int defaultSort, String username, String password, Date lastLogin)
{
this.Id = id;
this.Name = name;
this.DefaultSort = defaultSort;
this.Username = username;
this.LastLogin = lastLogin;
}
}
These users will be retrieved from an API - the IDs are stored in the Database as uniqueidentifiers (or GUIDs in C#).
When I enter a new record into the users table, everything works just fine:
DateTime dt = new DateTime();
UUID newUID = UUID.randomUUID();
UserObject newUser = new UserObject(newUID, "David", 1, "userOne", "password", dt.toDate());
newUser.save();
However, when I try and retrieve the value back out I get an error:
Class cannot be read from Sqlite3 database. Please check the type of field Id(java.util.UUID)
Does Sugar ORM (or SQLite) simply not support UUIDs? If I try with the Joda DateTime, replacing the "LastLogin", the table just won't build at all so it looks as if it can create the fields, just not retrieve/store them...
You should not use var with name Id. Sugar record uses Id to store index values. Use anything except Id
public class UserObject extends SugarRecord{
public UUID uId;
public String Name;
public int DefaultSort;
public String Username;
public Date LastLogin;
public UserObject()
{
}
public UserObject(UUID uId, String name, int defaultSort, String username, String password, Date lastLogin)
{
this.uId= uId;
this.Name = name;
this.DefaultSort = defaultSort;
this.Username = username;
this.LastLogin = lastLogin;
}
}
from the v1.4 it is no longer need to use SugarRecord
Sugar ORM won't be able to build the date object again when retrieving data from the database. If you take a look at your database, it's probably storing strings (that's the case with me, and I'm using JODA).
In my case I overcame this issue by using strings instead of data objects. You will have to parse them after you retrieve the data from the database, but I believe that's the only option you have, since SQLite only support a few data types.

Categories