多个订单对应一个用户
用户类:Customer
import lombok.Data; import javax.persistence.*; @Data @Entity(name = "ManyToOne_CUTOMERS") @Table(name = "ManyToOne_CUTOMERS") public class Customer { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(name = "LAST_NAME", length = 50, nullable = false) private String lastName; private String email; }
订单类:Order
import lombok.Data; import javax.persistence.*; @Data @Entity(name = "ManyToOne_ORDERS") @Table(name = "ManyToOne_ORDERS") public class Order { @Id @GeneratedValue private Integer id; @Column(name = "ORDER_NAME") private String orderName; // 映射单向 n-1 的关联关系 // 使用 @JoinColumn 来映射外键 // 使用 @ManyToOne 来映射多对一的关联关系 // 可使用 @ManyToOne 的 fetch 属性来修改默认的关联属性的加载策略,在左外连接和两条SQL间切换 @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "CUSTOMER_ID") private Customer customer; }
测试
建表
import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; public class JPAyingshe { private EntityManagerFactory entityManagerFactory; private EntityManager entityManager; private EntityTransaction transaction; @Before public void init() { entityManagerFactory = Persistence.createEntityManagerFactory("jpaname"); entityManager = entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); } @After public void destroy() { transaction.commit(); entityManager.close(); entityManagerFactory.close(); } @Test public void createTable() {} }
添加
/** * 保存多对一时, 建议先保存 1 的一端, 后保存 n 的一端, 这样不会多出额外的 UPDATE 语句 */ @Test public void testManyToOnePersist() { Customer customer = new Customer(); customer.setEmail("gg@163.com"); customer.setLastName("GG"); Order order1 = new Order(); order1.setOrderName("G-GG-1"); Order order2 = new Order(); order2.setOrderName("G-GG-2"); //设置关联关系 order1.setCustomer(customer); order2.setCustomer(customer); //执行保存操作 entityManager.persist(customer); entityManager.persist(order1); entityManager.persist(order2); }
查询
//默认情况下, 使用左外连接的方式来获取 n 的一端的对象和其关联的 1 的一端的对象. //可使用 @ManyToOne 的 fetch 属性来修改默认的关联属性的加载策略 @Test public void testManyToOneFind() { Order order = entityManager.find(Order.class, 12); System.out.println(order.getOrderName()); System.out.println(order.getCustomer().getLastName()); }
使用懒加载
// 可使用 @ManyToOne 的 fetch 属性来修改默认的关联属性的加载策略 @JoinColumn(name = "CUSTOMER_ID") @ManyToOne(fetch = FetchType.LAZY) public Customer getCustomer() { return customer; }
删除
// 不能直接删除 1 的一端, 有外键约束 @Test public void testManyToOneRemove() { Order order = entityManager.find(Order.class, 12); entityManager.remove(order); Customer customer = entityManager.find(Customer.class, 11); entityManager.remove(customer); }
修改
@Test public void testManyToOneUpdate(){ Order order = entityManager.find(Order.class, 12); order.getCustomer().setLastName("FFF"); }