3

I use Hibernate 4 to use mapping to a Postgres database. Before doing mapping i create first java entities. And then, i use a java class to generate sql script from my entities. Here is my entities :

User entity

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


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name="fistname")
    private String firstName;

    @Column(name="lastName")
    private String lastName;
....
}

Project entity

@Entity
@Table(name="projects")
public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name="title")
    private String title;

    @Column(name="description")
    private String description;
..
}

I've noticed that @GeneratedValue(strategy = GenerationType.AUTO) produces the same sequence for table myusers and projects. If i create the first record on myusers table the id will have "1" as value and then when i create the first record in table projects, this record will have id =2. They use both the same sequence. I want to know how i cannot modify my entities to specify to Hibernate to create a sequence for each table.

Bibhas Debnath
  • 14,559
  • 17
  • 68
  • 96
Pracede
  • 4,226
  • 16
  • 65
  • 110
  • possible duplicate of [Hibernate: rundown on how @GeneratedValue works](http://stackoverflow.com/questions/11788483/hibernate-rundown-on-how-generatedvalue-works) – Peter Bratton Feb 11 '14 at 14:44

1 Answers1

8

If you're on a recent Hibernate, try:

@GeneratedValue(strategy = GenerationType.IDENTITY)

If it still uses a sequence per table use:

@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="mytable_id_seq")
@SequenceGenerator(name="mytable_id_seq", sequenceName="mytable_id_seq", allocationSize=1)

See hibernate could not get next sequence value

Community
  • 1
  • 1
Craig Ringer
  • 307,061
  • 76
  • 688
  • 778