具有重叠列的Hibernate / JPA ManyToOne映射

时间:2017-11-29 16:15:12

标签: java hibernate jpa

注意:这是针对旧项目的,我无法将所有内容更改为生成的代理ID。

我有一个带嵌入式复合键的实体,带有实体ID和客户端ID。

@Embeddable
public class EntityId {
  @Column(name=COL_EID)
  @NotNull
  private String eid;

  @Column(name=COL_CID)
  private String cid;
}

@Entity
public class Customer {

  @Id @Embedded @Valid
  @AttributeOverrides({
    @AttributeOverride(name=EntityId.FIELD_EID, column=@Column(name=COL_EID)),
    @AttributeOverride(name=EntityId.FIELD_CID, column=@Column(name=COL_CID))
  })
  private EntityId id;

  // Other stuff
}

@Entity
public class MyNewOrder {

  @Id @Embedded @Valid
  @AttributeOverrides({
    @AttributeOverride(name=EntityId.FIELD_EID, column=@Column(name=COL_EID)),
    @AttributeOverride(name=EntityId.FIELD_CID, column=@Column(name=COL_CID))
  })
  private EntityId id;

  @NotNull
  @ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.ALL }, optional = false)
  @JoinColumns({
      @JoinColumn(name = "customer_EID", referencedColumnName = "EID", nullable = false, insertable = false, updatable = false),
      @JoinColumn(name = "CID", referencedColumnName = "CID", nullable = false, insertable = false, updatable = false) })
  private Customer customer;
}

所以这是发生了什么的最小样本。我希望在我的" MyNewOrder"中获得客户EID。表,但CID重叠,即:

MyNewOrder:[EID,CID,customer_EID]

整个方法有点复杂,但它是这样的:

@In Session session;

public void myMethod() {
  Transaction t = null;       
  try {
    t = session.beginTransaction();

    Customer c = (Customer) session.get(Customer.class, "the ID");
    MyNewOrder order = new MyNewOrder();
    order.setCustomer(c);
    session.persist(order);

    t.commit();
  }
} catch (Exception ex) {
  t.rollback();
}

这是在JBoss AS 7.1上运行,使用Hibernate 4.2。 在调试器中,一切看起来都很好,我找到了正确的客户,所有ID都已设置,我没有得到任何异常,但在数据库中我得到一行:

  

MyNewOrder [eid1,cid1,NULL]

编辑: 当我完全删除@JoinColumns时它会起作用,但我需要添加一个多余的' customer_CID'列。

0 个答案:

没有答案