Hibernate:映射@OneToMany / @ManyToOne问题(不使用实体主键)

时间:2011-09-12 12:29:42

标签: java hibernate orm annotations persistence

我是Hibernate / Spring的新手,试图在创建一个小的Web实用程序时映射遗留数据库,这可以简化同事的一些工作。由于我已经映射了实体并且可以访问基础数据,因此我还有一些问题。长话短说,我有两个客户,客户

@Entity
public class Customer implements Serializable{

    @Id
    @Column(name = "RecordID")
    private Integer id;

    @Column(name = "CUSTOMERNAME1")
    private String name;

    @OneToMany
    @JoinColumn(name="CUSTOMER1", referencedColumnName="CUSTOMERNAME1")
    private List<Contract> contracts;
}

和合同:

@Entity
public class Contract implements Serializable {

    @Id
    @Column(name = "RECORDID") //RecordID
    private Integer id;

    @Column(name = "CONTRACTID1") //ContractID1
    private String contractId;

    @Column(name = "CUSTOMER1") //Customer1
    private String customerName;

    //@ManyToOne
    //private Customer customer;  // how can I write the reverse mapping?
}

从客户到合同的映射工作(一个客户可以有很多合同,我可以使用客户中的列表合同字段获取所有合同,但我的问题是,我如何实现相反 - 即,让客户,到要签约的是哪个?

1 个答案:

答案 0 :(得分:2)

Java API提供了一些如何使用ManyToOne批注的示例: http://java.sun.com/javaee/6/docs/api/javax/persistence/ManyToOne.html

如下所示:

客户类:

@OneToMany(mappedBy="customer", cascade=CascadeType.ALL)
private List<Contract> contracts;

合同类:

@ManyToOne
@JoinColumn(name="customer_id", nullable=false)
private Customer customer;