how to implement auto increment id field per table with Hibernate and postgresql for one to many relationships

12,285

Ok, from Hibernate use of PostgreSQL sequence does not affect sequence table cited by a_horse_with_no_nameless,

I managed to set the auto incremented primary keys of every referenced tables like these:

@Id
@SequenceGenerator(name="pk_sequence",sequenceName="messagesounds_id_seq", allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="pk_sequence")
private int id;

Thanks a lot for all the research.

Share:
12,285
Capitaine
Author by

Capitaine

With 10+ years of relevant web programming experience, I can help you with specific tasks. I could communicate in English, Cantonese, Chinese, German, and intermediate Japanese. PM if interested: carsonng2000 [at] gmail

Updated on June 27, 2022

Comments

  • Capitaine
    Capitaine about 2 years

    I have 4 entities one-to-many Message entity:

    @Entity
    @Table(name = "Messages")
    public class Message {
    ...
        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "messagesounds_id")
        private Sound sound;
    
        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "messagevibrations_id")
        private Vibration vibration;
    
        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "messagecolors_id")
        private Color color;
    
        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "messageplatforms_id")
        private Platform platform;
    ...
    }
    

    whereas other 4 entities look like this:

    @Entity
    @Table( name = "MessageSounds"  , uniqueConstraints=@UniqueConstraint(columnNames = {"name"}))
    public class Sound {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private int id;
    
        @OneToMany(cascade={CascadeType.ALL})
        @JoinColumn(name="messagesounds_id")
        private Set<Message> message;
    ...
    }
    

    I can successfully create the first message record referenced to those first records of the 4 referenced tables. But the message table in postgresql db looks like this:

     id |...| messagesounds_id | messagevibrations_id | messagecolors_id | messageplatforms_id |
     1  |...| 2 | 3 | 4 | 5 |
    

    I want to let every primary key of the 4 referenced tables be auto incremented, so that the first record of message table should look like this:

     id |...| messagesounds_id | messagevibrations_id | messagecolors_id | messageplatforms_id |
     1  |...| 1 | 1 | 1 | 1 |
    

    How to achieve this using annotations?

  • Capitaine
    Capitaine about 11 years
    i have tried that and I am using postgresql. And please just don't copy from other answers without citing sources.