import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
@Entity
@Table(name = "t_customers")
public class Customer
{
private int id;
private String name;
private Referee referee;
private Collection<Order> orders;
private Collection<Address> addresses;
@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinTable(name = "t_customers_addresses", joinColumns = @JoinColumn(name = "customer_id",
referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "address_id", referencedColumnName = "id"))
public Collection<Address> getAddresses()
{
return addresses;
}
... ...
}
Address类的代码如下:
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name="t_addresses")
public class Address
{
private int id;
private String addressLine;
private String country;
private String postCode;
private Collection<Customer> customers;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getAddressLine()
{
return addressLine;
}
public void setAddressLine(String addressLine)
{
this.addressLine = addressLine;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
public String getPostCode()
{
return postCode;
}
public void setPostCode(String postCode)
{
this.postCode = postCode;
}
@ManyToMany(mappedBy="addresses")
public Collection<Customer> getCustomers()
{
return customers;
}
public void setCustomers(Collection<Customer> customers)
{
this.customers = customers;
}
}
customer.setName("微软11");
List<Address> addresses = new ArrayList<Address>();
Address address = new entity.Address();
address.setAddressLine("address1");
address.setCountry("中国");
address.setPostCode("12345678");
addresses.add(address);
address = new entity.Address();
address.setAddressLine("address2");
address.setCountry("美国");
address.setPostCode("4321");
addresses.add(address);
customer.setAddresses(addresses);
em.persist(customer);