@EmbeddedId with @GeneratedValue in @Embeddable

后端 未结 1 653
时光取名叫无心
时光取名叫无心 2020-12-21 18:30

I have a MySQL DB with the following structure (excerpt):

CREATE TABLE MENU(
    id_menu    TINYINT      UNSIGNED    NOT NULL    AUTO_INCREMENT,
    name             


        
相关标签:
1条回答
  • 2020-12-21 18:59

    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 and as the associated column is an auto-increment column then this will be the case.

    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.

    So, while the PK for the associated table may be configured as PRIMARY KEY (id_operation, id_menu) it would seem, id_operation, through being auto-increment, could stand alone as a PK and therefore Operation can be mapped as below:

    @Entity
    public class Operation{
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        @ManyToOne
        @JoinColumn(name = "id_menu")
        private Menu menu;
    }
    

    If you create the relevant IDClass then OperationRole can be mapped as below. For an example of this scenario and how the ID class would loook see:

    https://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Example_JPA_2.0_ManyToOne_id_annotation

    @Entity
    @IdClass(OperationRolePk.class)
    public class OperationRole{
    
            @Id
            @ManyToOne
            @JoinColumn(name = "id_operation")
            private Operation operation;
    
            @Id
            @ManyToOne
            @JoinColumn(name = "id_menu")
            private Menu menu;
    
            @Id
            @ManyToOne
            @JoinColumn(name = "id_user")
            private User user;
    }
    
    0 讨论(0)
提交回复
热议问题