ManyToOne question
andrewi Sep 15, 2005 1:25 AMhi
Lets say I have customer that can have many different stores. How do I create the relationship between them. I get the OneToOnes but can't seem to master the ManyToOne relationships.
I have included the latest (non) working attempt.
Can someone please point me in the right direction.
thanks
@Entity
@Table(name = "CUSTOMER")
public class CustomerCMP implements java.io.Serializable{
private Long id;
private String name;
private String contact;
private AddressCMP address;
private List<StoreCMP> StoreList;
public CustomerCMP(){}
public CustomerCMP(String Name, String Contact)
{
// Debug.print("Create", this);
this.name = Name;
this.contact = Contact;
}
@Id(generate = GeneratorType.AUTO)
@Column(name = "customerId", nullable = false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="CONTACT")
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
@OneToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "addressId")
public AddressCMP getAddress() {
return address;
}
public void setAddress(AddressCMP address) {
this.address = address;
}
@OneToMany(mappedBy="customerCMP", cascade={CascadeType.PERSIST}, fetch=FetchType.EAGER)
@JoinColumn(name="customerId")
public List<StoreCMP> getStoreList()
{
return StoreList;
}
public void setStoreList(List<StoreCMP> StoreList)
{
this.StoreList = StoreList;
}
public StoreCMP addToStoreList(StoreCMP store)
{
getStoreList().add(store);
store.setCustomer(this);
return store;
}
public StoreCMP removeFromStoreList(StoreCMP store)
{
getStoreList().remove(store);
store.setCustomer(null);
return store;
}
}
@Entity
@Table(name = "STORE")
public class StoreCMP implements Serializable
{
private Long id;
private String name;
private AddressCMP address;
private String code;
private CustomerCMP customer;
public StoreCMP()
{
}
public StoreCMP(Long id, String Name, AddressCMP address, String code )
{
setId(id);
setName(name);
setAddress(address);
setCode(code);
}
@Id(generate = GeneratorType.AUTO)
@Column(name="StoreId", nullable=false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@OneToOne(cascade = {CascadeType.ALL}, fetch=EAGER)
@JoinColumn(name = "ADDRESSID")
public AddressCMP getAddress() {
return address;
}
public void setAddress(AddressCMP address) {
this.address = address;
}
@Column(name="CODE")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Column(name="NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne
@JoinColumn(name="customerId")
public CustomerCMP getCustomer()
{
return customer;
}
public void setCustomer(CustomerCMP customer)
{
this.customer = customer;
}
}