我在尝试创建组合密钥(EmbeddedId)时遇到了Ebean问题。
这是我所拥有的草稿:
@Entity public class EntityA extends Model{
@Id
private String ID;
@OneToMany
private List<EntityB> listEntitesB;
public EntityA(){
ID = UUID.randomUUID();
}
}
@Entity public class EntityB extends Model{
@EmbeddedId
private EntityB_PK ID;
@ManyToOne
@JoinColumn(name="entityA_fk", referencedColumnName="listEntitiesB")
private EntityA entityA;
public EntityB(String entityB_ID){
ID = new EntityB_PK(UUID.randomUUID(), entityB_ID);
}
}
@Embeddable public class EntityB_PK{
private String entityB_ID;
private String entityA_FK_ID;
public EntityB_PK(String entB_ID, String entA_FK_ID){
entityB_ID = entB_ID;
entityA_FK_ID = entA_FK_ID;
}
}
注意:我使用Ebean 4.1.4和Java 1.6。
所以,这段代码运行良好,但有一个特权,我试图解决 - 数据库中的结果表如下所示:
正如您所看到的那样,考虑到&#34; entityA_FK_ID&#34;列。
我想要什么?
答案 0 :(得分:1)
要解决这个问题,我们必须:
以下是代码:
EntityA.java:
@Entity
public class EntityA extends Model {
@Id
private String ID;
@OneToMany(mappedBy="entityA")
public List<EntityB> listEntitesB;
public static Finder<String,EntityA> find = new Finder<String,EntityA>(
String.class, EntityA.class
);
public EntityA() {
ID = UUID.randomUUID().toString();
}
public String getID() {
return ID;
}
}
EntityB.java:
@Entity
public class EntityB extends Model {
@EmbeddedId
private EntityB_PK ID;
@ManyToOne
@JoinColumn(name = "entityA_fk_id", insertable = false, updatable = false)
private EntityA entityA;
public EntityA getEntityA() {
return entityA;
}
public void setEntityA(EntityA aEntityA) {
entityA = aEntityA;
ID.entityA_FK_ID = aEntityA.getID();
}
public EntityB(String entityB_ID){
ID = new EntityB_PK(UUID.randomUUID().toString(), entityB_ID);
}
public String getID() {
return ID.entityB_ID;
}
}
EntityB_PK.java:
@Embeddable
public class EntityB_PK implements Serializable {
public String entityB_ID;
@Column(name="entityA_fk_id")
public String entityA_FK_ID;
public EntityB_PK(String entB_ID, String entA_FK_ID){
entityB_ID = entB_ID;
entityA_FK_ID = entA_FK_ID;
}
@Override
public int hashCode() {
return entityB_ID.length() + entityA_FK_ID.length();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
EntityB_PK b = (EntityB_PK)obj;
if(b==null)
return false;
if (b.entityB_ID.equals(entityB_ID) && b.entityA_FK_ID.equals(entityA_FK_ID)) {
return true;
}
return false;
}
}