@Id in sleep mode

I have code

@Entity
@Table(name = "USER")
public class User {

    @Id
    @Column(name = "id", nullable = false, unique = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

      

When I try to add a user to the table, I catch

org.h2.jdbc.JdbcSQLException: NULL not allowed for column "ID"; SQL statement:
insert into USER (id, birthday, email, first_name, last_name, login, password, id_role) values (null, ?, ?, ?, ?, ?, ?, ?) [23502-181]

      

This is my code for adding user to db

stock2.setBirthday(new Date(46));
stock2.setEmail("sss");
stock2.setFirstName("oleg");
stock2.setId(506l);
stock2.setLastName("gubov");
stock2.setLogin("OP");
stock2.setPassword("1");
Role role2 = new Role();
role2.setName("poil");
role2.setId(7l);
stock2.setRole(role2);

HibernateUserDao dao = new HibernateUserDao();
System.out.println(stock2.getId() + " -----------before");
dao.create(stock2);

      

and the create method code:

public void create(User user) {

    Session session = null;
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();
    } catch (Exception e) {
        session.getTransaction().rollback();
        throw e;
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
}

      

In my opinion, id is 7, but not NULL. And "java" thinks differently. Where could the problem be?

+3


source to share


3 answers


You are calling dao.create()

, so you intend to insert a row into the database. Why are you using GenerationType.IDENTITY

inserting your own id

?

GenerationType.IDENTITY

means yours JPA Provider

will use the column IDENTITY

(so it id

will be assigned from the database side). Hibernate, knowing it won't post your id

in the SQL statement.



By the way, this is not the best option for creating identifiers. GenerationType.IDENTITY

has some performance issues (it doesn't support preallocation and JPA Provider

might make a query SELECT

after every inserted row, just to see what was generated id

).

To be able to insert your own values ​​like id

, you can simply remove @GeneratedValue

(which de facto means you want it to be id

automatically generated) annotations.

+2


source


User is a reserved keyword for most database engines, so change:

@Table(name = "USER")

      



to

@Table(name = "APP_USER")

      

0


source


Here is a link describing your problem and suggesting possible solutions: http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Common_Problems_4

Excerpts:

null is inserted into the database or an insert error.

[...] You may have also left out that your primary key column in your table is an identity type.

0


source







All Articles