qwer re
qwer re

Reputation: 41

@Id in hibernate

I have some 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 user to 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 to add 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 code of create method:

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 otherwise. Where can be the problem?

Upvotes: 3

Views: 3169

Answers (3)

cooltea
cooltea

Reputation: 1113

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

Excerpt:

null is inserted into the database, or error on insert.

[...] It may also be that you did not set your primary key column in your table to be an identity type.

Upvotes: 0

Maciej Dobrowolski
Maciej Dobrowolski

Reputation: 12122

You call dao.create(), so your intention is to insert row into database. Why are you using GenerationType.IDENTITY while inserting your own id?

GenerationType.IDENTITY means that your JPA Provider will make use of table's IDENTITY column (so, the id will be assigned at databse side). Hibernate, knowing that, will not send your id in an SQL statement.

By the way, it is not the best option for generating ids. GenerationType.IDENTITY has some performance problems (it does not support preallocation and JPA Provider may make SELECT query after each inserted row, just to know what the generated id was).

To be able to insert your own values as ids you can simply remove @GeneratedValue (which de facto means that you want ids to be generated automatically) annotation.

Upvotes: 2

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153700

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

@Table(name = "USER")

to

@Table(name = "APP_USER")

Upvotes: 0

Related Questions