一:单项多对一的关联关系
例如:订单和客户
1.新创建订单类
package com.atguigu.jpa.helloworld; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table; @Table(name = "JPA_ORDERS")
@Entity
public class Order { private Integer id ;
private String orderName;
private Customer customer; @GeneratedValue
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
} @Column(name = "ORDER_NAME")
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
//映射单向多对一n-1的关联关系
//使用@ManyToOne来映射多对一的关联关系
//使用@JoinColumn来映射外键
@JoinColumn(name = "CUSTOMER_ID")
@ManyToOne
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
} }
配置文件persistence.xml添加:
<!-- 添加持久化类 -->
<class>com.atguigu.jpa.helloworld.Order</class>
进行测试:
1)保存测试:
/**
* 保存多对一时,建议先保存1的一段,后保存n的一端,
* 这样不会多出额外的update语句
*/
@Test
public void testManyToOnePersist(){
Customer customer = new Customer();
customer.setAge(188);
customer.setBirth(new Date());
customer.setCreatedDate(new Date());
customer.setEmail("fffff.emal");
customer.setLastName("ffffff"); Order order1 = new Order();
order1.setOrderName("O-FF-1"); Order order2 = new Order();
order2.setOrderName("O-FF-2"); //设置关联关系
order1.setCustomer(customer);
order2.setCustomer(customer); //执行保存操作
entityManager.persist(customer);
entityManager.persist(order1);
entityManager.persist(order2);
}
2)获取测试:
/**
* 默认情况下,使用做外连接的方式获取n的一端的对象和其关联的1的一端的对象
* 可使用@ManyToOne的fetch属性来修改默认的关联属性的加载策略
*/
@Test
public void testManyToOneFind(){
Order order = entityManager.find(Order.class, 1);
System.out.println(order.getOrderName()); System.out.println(order.getCustomer().getLastName());
}
输出:
使用懒加载的方式:
//映射单向多对一n-1的关联关系
//使用@ManyToOne来映射多对一的关联关系
//使用@JoinColumn来映射外键
//可使用@ManyToOne的fetch属性来修改默认的关联属性的加载策略
@JoinColumn(name = "CUSTOMER_ID")
@ManyToOne(fetch = FetchType.LAZY)
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
输出:
3)删除测试
/**
* 不能直接删除1 的一端,因为有外键约束
*/
@Test
public void testManyToOneRemove(){
/*Order order = entityManager.find(Order.class, 1);
entityManager.remove(order);*/ Customer customer = entityManager.find(Customer.class, 1);
entityManager.remove(customer); }
4)更新测试
@Test
public void testManyToOneUpdate(){
Order order = entityManager.find(Order.class, 1);
order.getCustomer().setLastName("FFFF");
}