开发者

Hibernate: mapping @OneToMany / @ManyToOne problems (not using entity primary keys)

开发者 https://www.devze.com 2023-04-04 19:14 出处:网络
I am new to Hibernate / Spring, trying to map legacy database while creating a little web utility, which should ease some work for the colleagues. As I had mapped the entities and have access to the u

I am new to Hibernate / Spring, trying to map legacy database while creating a little web utility, which should ease some work for the colleagues. As I had mapped the entities and have access to the underlying data, I have some issues further down 开发者_JAVA技巧the road. To make long story short, I have two entites, Customer

@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;
}

and Contract:

@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?
}

The mapping from Customer to Contracts works (one customer can have many contracts, I can get them all using List contracts field in customer, but my question is, how can I achieve the reverse - that is, get the customer, to which to contract is mapped?


The Java API has some examples of how to use the ManyToOne annotation: http://java.sun.com/javaee/6/docs/api/javax/persistence/ManyToOne.html

something like the below:

Customer class:

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

Contract class:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号