Customer类
@Table(name="jpa_customer") @Entity public class Customer { @Column(name="id") @GeneratedValue(strategy=GenerationType.AUTO) @Id private Integer id; @Column(name="last_name") private String lastName; private String email; private int age; //省略getter setter }
Order类
@Table(name = "jps_order") @Entity public class Order { @GeneratedValue @Id private Integer id; @Column(name = "order_name") private String orderName; @JoinColumn(name = "customer_id") // 外键 @ManyToOne(fetch=FetchType.LAZY)//懒加载 // 映射多对一的关联关系 private Customer customer; //省略getter setter }
测试
//保存多对一时,建议先保存1,后保存n。这样就不会多发送额外的update语句 @Test public void testManyToOnePersist() { Customer customer = entityManager.find(Customer.class, 6); Order order1 = new Order(); order1.setOrderName("订单1"); order1.setCustomer(customer); Order order2 = new Order(); order2.setOrderName("订单2"); order2.setCustomer(customer); entityManager.persist(order1); entityManager.persist(order2); } //默认情况下使用左外连接来获取n端的对象和其关联的1端的对象 @Test public void manyToOneFind() { Order order = entityManager.find(Order.class, 1); Customer customer = order.getCustomer(); System.out.println(customer); } @Test public void manyToOneRemove() { Order order = entityManager.find(Order.class, 1); //entityManager.remove(order);//可以直接删除 Customer customer = order.getCustomer(); // entityManager.remove(customer);//不能直接删除,有外键约束 } @Test public void manyToOneUpdate() { Order order = entityManager.find(Order.class, 1); order.getCustomer().setLastName("new name"); //commit之后执行update }
原文地址:http://shamrock.blog.51cto.com/2079212/1707464