Spring data JPA only one composite key is auto incremented issue

后端 未结 2 1950
忘了有多久
忘了有多久 2021-01-16 10:58

I am using MySQL database.

In my table i there are two four primary keys, out of which one is auto incremented.

@Embeddable
    public class Employee         


        
相关标签:
2条回答
  • 2021-01-16 11:14

    Your JPA @Id does not need to match the database PK column(s). So long as it is unique then that is all that matters.

    From https://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing:

    The JPA Id does not always have to match the database table primary key constraint, nor is a primary key or a unique constraint required.

    As your an auto-increment column is guaranteed to be unique then just use gender_key as your @ID and map id as a normal column.

    @Entity
    @Table(name = "employee")
    public class employee {
    
       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY) 
       private int genderKey;
    
       @Column
       private int id;
    
    }
    

    To be honest I would find your schema confusing however.

    I would also suggest reading the following:

    https://www.javatpoint.com/java-naming-conventions

    0 讨论(0)
  • 2021-01-16 11:29

    You're missing a @GeneratedValue at the id field. Depending on its values, you're free to choose a strategy for generation, like a sequences, id tables, an automatic internal id generation. Last but not least GenerationType.AUTO will choose one of the mentioned strategies. See the Javadocs for javax.persistence.GeneratedValue and javax.persistence.GenerationType.

    0 讨论(0)
提交回复
热议问题