how to make a composite primary key (java persistence annotation)

前端 未结 5 1072
天命终不由人
天命终不由人 2020-11-29 06:05

How to make it so that the table user_roles defines the two columns (userID, roleID) as a composite primary key. should be easy, just can\'t remember/find.

In

5条回答
  •  余生分开走
    2020-11-29 06:29

    Composite keys are done using @IdClass (the other way is using @EmbeddedId and @Embeddable not sure which one you are looking for) the @IdClass is as follows

    @Entity
    @IdClass(CategoryPK.class)
    public class Category {
        @Id
        protected String name;
    
        @Id
        protected Date createDate;
    
    }
    
    public class CategoryPK implements Serializable {
    
        String name;
    
        Date createDate;
    
        public boolean equals(object other) {
            //implement a equals that the PP can use to determine 
            //how the CategoryPK object can be identified.
        }
    
        public int hashCode(){
            return Super.hashCode();
        }
    }
    

    my Category here will be your user_roles and the name and createDate will be your userid and roleid

提交回复
热议问题