Issue
I am making an application with users. A user has an id, which is automatically assigned using the following Hibernate annotation:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id
That is all fine and dandy, however the problem is that every time I run the application (while adding the same user) it assigns a new id to the user, regardless if the user already exists.
What can I do that makes it so an existing user doesn't get a new id every time I run the application without having to request all users to check their username individually?
Thanks in advance.
EDIT
Some more code examples (I will only write relevant code here).
The User:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
// more code here
}
The User hibernate class with the save function: (The session is opened in Main and given to the constructor).
public class UserDAOHibernate implements GebruikerDAO {
private Session session;
public UserDAOHibernate(Session session) {
this.session = session;
}
@Override
public boolean save(User user) {
try {
if (this.findById(user.getId()) == null) {
Transaction transaction = session.beginTransaction();
session.save(user);
transaction.commit();
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
// more code here
}
The above code where I check if the user already exists based on the id doesn't work because of the fact that the user keeps getting new ids. So this function checks if there exists a user with id = 2, while the one that already exists has id = 1.
In Main:
// lots of code
User user = new User("Stijuh");
// more code here
UserDAOHibernate udao = new UserDAOHibernate(session);
udao.save(user);
Solution
When you want to update, before saving the object, you have to set the id field. This way Hibernate will not generate a new one
Answered By - Pedro
Answer Checked By - Mildred Charles (JavaFixing Admin)