JPA / Hibernate OneToMany Mapping, using a composite PrimaryKey

僤鯓⒐⒋嵵緔 提交于 2019-11-30 03:48:22

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;
}

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;
    ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!