2

I am a newbie in hibernate and was playing around with it. For an unique field in an entity I am setting @GeneratedValue annotation to it. Suppose I have two entities , user and company and both having an unique id with @GeneratedValue annotation . When I save both the entities using hibernate session factory , the id generated are 1 and 2 respectively , where it should be 1 each for both entities. The next time when i save both , id generated are 3 and 4 . So my guess is that , @GeneratedValue is working in db level and not table level. How to make it table level ?

Adding some codes and configs.

User entity

@Entity @Table(name="user") public class User { @Id @GeneratedValue @Column(name = "id") private Integer id; } 

Company entity

@Entity @Table(name="company") public class Company { @Id @GeneratedValue @Column(name = "id") private Integer id; } 

Saving using hibernate session

Session session = sessionFactory.getCurrentSession(); User user = new User(); session.save(user); Company company = new Company(); session.save(company); 

Result

mysql> select * from user;
+-----+ | id | +-----+ | 234 | +-----+

mysql> select * from company;
+-----+ | id | +-----+ | 235 | +-----+

For the records , I am using hibernate-jpa-2.1-api ( 1.0.0.Draft-16 ) with hibernate 5.

1
  • It actually should generate 1 for both entities by default. Show us your config and some code please. Commented Apr 20, 2016 at 11:56

1 Answer 1

3

The @GenerateValue annotation has an attribute called strategy that can hold one of the the following strategies for generate the values for a primary keys:

  • GenerationType.AUTO
  • GenerationType.IDENTITY
  • GenerationType.SEQUENCE
  • GenerationType.TABLE

The GenerationType.AUTO use a global number generator for a database and it is the default, so if you only define @GenerateValue in the variable, you will have this behavior.

I recommend to you use one of the others in the list for obtain the result that you expect.For example, the GenerationType.IDENTITY allow you to generate the keys using the value from the table, only if the primary key is an auto-generated type. For example in Postgres, you can use the data type SERIAL and use this for generate the value of the key.

Sign up to request clarification or add additional context in comments.

3 Comments

If i use that , the id is not generated and i am getting "Field 'id' doesn't have a default value " error while saving . Code : @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "id") private Integer id;
As I said in the response the primary key data type in the database must be an autogenerated type, here are some examples of autogenerated types in some RDBMSs link
FYI , the field is having AUTO_INCREMENT option . Hibernate is not allowing to save as the validation itself fails.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.