Ebean EmbeddedId映射列到ManyToOne关系

尝试创建组合键(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一起使用。

因此,此代码运行良好,但存在一个我正在尝试解决的问题-数据库中的结果表如下所示:

  • entityB_ID [主要]
  • entityA_FK_ID [主要]
  • 实体A_fk

如您所见,考虑到“ entityA_FK_ID”列,最后一列是多余的。

  • 我希望能够告诉Ebean为关联@ManyToOne使用列“ entityA_FK_ID”,而不是创建它自己的列。

回答:

为了解决这个问题,我们必须:

  1. 将EntityB.entityA映射到与EntityB.ID.entityA_FK_ID相同的列
  2. 设置EntityB.entityA @JoinColumn批注的’insertable’和’updateable’属性
  3. EntityB.entityA的替代设置器

这是代码:

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;

}

}

以上是 Ebean EmbeddedId映射列到ManyToOne关系 的全部内容, 来源链接: utcz.com/qa/398062.html

回到顶部