按照此链接
我想使用 OneToMany 代替 ManyToMany 注释,使用 Ebean 使中间类具有复合键。我有这个错误:
java.lang.RuntimeException:读取模型注释时出错。SoftwareTagPk
这是我的 SoftwareTagPk 类:
@Embeddable
public class SoftwareTagPk implements Serializable {
@ManyToOne
private Tag tag;
@ManyToOne
private Software software;
...
}
和 SoftwareTag 类:
@Entity
public class SoftwareTag extends Model {
@EmbeddedId
private SoftwareTagPk pk = new SoftwareTagPk();
@Transient
public Tag getTag() {
return pk.getTag();
}
public void setTag(Tag aTag) {
pk.setTag(aTag);
}
@Transient
public Software getSoftware() {
return pk.getSoftware();
}
public void setSoftware(Software aSoftware) {
pk.setSoftware(aSoftware);
}
}
也在日志中:
与 [class models.Tag] 关联时出错 [models.SoftwareTagPk.tag]。类models.Tag注册了吗?
如何解决?
要使此代码正常工作,您必须执行以下操作:
SoftwareTagPk
类中仅放置标签和软件的ID@ManyToOne
关系移至 SoftwareTag
类@JoinColumn
注释,并将属性 updatable
和 insertable
设置为 false。setTag
类中的设置器 setSoftware
和 SoftwareTag
。在这些设置器中,您将重写 id 为复合键。该解决方案的主要思想是
SoftwareTag
具有复合键和@ManyToOne
关系,并且它们映射到相同的列。
这是代码:
标签.java
@Entity
public class Tag extends Model {
@Id
private Integer id;
@OneToMany(mappedBy="tag")
public List<SoftwareTag> softwareTags;
public Integer getId() {
return id;
}
public void setId(Integer aId) {
id=aId;
}
public static Finder<Integer,Tag> find = new Finder<Integer,Tag>(
Integer.class, Tag.class
);
}
软件.java
@Entity
public class Software extends Model {
@Id
private Integer id;
@OneToMany(mappedBy="software")
public List<SoftwareTag> softwareTags;
public Integer getId() {
return id;
}
public void setId(Integer aId) {
id=aId;
}
}
软件标签.java
@Entity
public class SoftwareTag extends Model {
SoftwareTag() {
pk = new SoftwareTagPk();
}
@EmbeddedId
private SoftwareTagPk pk = new SoftwareTagPk();
@ManyToOne
@JoinColumn(name = "tag_id", insertable = false, updatable = false)
private Tag tag;
@ManyToOne
@JoinColumn(name = "software_id", insertable = false, updatable = false)
private Software software;
public Tag getTag() {
return tag;
}
public void setTag(Tag aTag) {
tag = aTag;
pk.tag_id = aTag.getId();
}
public Software getSoftware() {
return software;
}
public void setSoftware(Software aSoftware) {
software = aSoftware;
pk.software_id = aSoftware.getId();
}
}
SoftwareTagPk.java
@Embeddable
public class SoftwareTagPk implements Serializable {
public Integer tag_id;
public Integer software_id;
@Override
public int hashCode() {
return tag_id + software_id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
SoftwareTagPk pk = (SoftwareTagPk)obj;
if(pk == null)
return false;
if (pk.tag_id.equals(tag_id) && pk.software_id.equals(software_id)) {
return true;
}
return false;
}
}