Home > OS >  hibernate identifier problem with User creation
hibernate identifier problem with User creation

Time:11-05

I have this problem here : org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned beforeQuery calling save() ...

I saw another topic but I can't understand the answer or if it's the same as me.

Here is my code :

@Entity
@Table(name = "USERS")

public class User {
    @Id
    @Column(name = "loginU")
    private String loginU;

    private String mailU;

    private String pwdU;


    public User(String login, String email, String password) {
        this.loginU = login;
        this.mailU = email;
        this.pwdU = password;
    }
 /**
     * Crée un utilisateur.
     */
    public User createUser(String login, String email, String password) {
        User user = getUserByLogin(login);
        if (user == null) {
            user = new User(login, email, password);
            em.persist(user);
        } else {
            return null;
        }
        return user;
    }
public User newUser(String login, String email, String password) {
        em.getTransaction().begin();
        User user = userDAO.createUser(login, email, password);
        em.getTransaction().commit();
        return user;
    }

I don't understand why hibernate wants a identifier since I'm giving it one with my User constructor ?

Thanks for reading me.

CodePudding user response:

You missing @GeneratedValue

@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
@Column(name = "loginU", nullable = false)
private String loginU;

CodePudding user response:

you can use @PrePersist but make sure loginU column length should be 36 characters

@PrePersist
public void autofill() {
    this.setLoginU(UUID.randomUUID().toString());
}
  • Related