JPA / Hibernate OneToMany Mapping, using a composite PrimaryKey

前端 未结 2 1654
孤城傲影
孤城傲影 2020-12-28 08:47

I\'m currently struggling with the right mapping annotations for a scenario using a composite Primary Key Class. First, what I am trying to achieve in words:

I have

相关标签:
2条回答
  • 2020-12-28 09:38

    In your code, EntityManager cannot resolve mappedBy attribute fieldAccessRulePK.group.

    Reason

    EntityManager assume that FieldAccessRule entity have an attribute name with fieldAccessRulePK.group during the FieldInjection.

    According to Java Naming Variables Rule, you cannot name fieldAccessRulePK.group by using characters dot > '.'

    Java Naming Variables Rule Reference

    All variable names must begin with a letter of the alphabet, an underscore ( _ ), or a dollar sign ($). The rest of the characters may be any of those previously mentioned plus the digits 0-9. The convention is to always use a letter of the alphabet. The dollar sign and the underscore are discouraged.

    One more thing:

    Don't use group instance in your FieldAccessRulePK embeddable class. For more reference here.

    Try as below :

    @Embeddable
    public class FieldAccessRulePK implements Serializable{
        @Column(name = "FIELD_KEY")
        private String fieldKey;
        @Column(name = "GROUP_ID")
        private String groupId;
    }
    
    public class FieldAccessRule {
        @EmbeddedId
        private FieldAccessRulePK id;
    
        @ManyToOne
        @JoinColumn(name = "GROUP_ID", referencedColumnName = "ID")
        private Group group;
    }
    
    
    public class Group{
        @OneToMany(mappedBy = "group")
        private Set<FieldAccessRule> fieldAccessRules;
    }
    
    0 讨论(0)
  • 2020-12-28 09:40

    I've fixed a similar problem by modifying the mappedBy attribute of the parent class (using dotted notation)

    public class Group{
        ...
        @OneToMany(mappedBy = "fieldAccessRulePK.group")
        private Set<FieldAccessRule> fieldAccessRules;
        ... 
    }
    

    and by keeping the annotations in the PK class:

    @Embeddable
    public class FieldAccessRulePK implements Serializable{
        private String fieldKey;
    
        @ManyToOne
        @JoinColumn(name = "group_id")
        private Group group;
        ...
    }
    
    0 讨论(0)
提交回复
热议问题