JPA学习笔记-映射单向一对多的关联关系

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;
	
	@JoinColumn(name="customer_id")//外键名
	@OneToMany(fetch=FetchType.EAGER, cascade={CascadeType.REMOVE})//映射一对多的关联关系,默认使用懒加载。cascade设置级联删除。
	private Set<Order> orders = new HashSet<>();
	
	//省略getter setter
}


Order类

@Table(name = "jps_order")
@Entity
public class Order {
	@GeneratedValue
	@Id
	private Integer id;
	@Column(name = "order_name")
	private String orderName;
	//省略getter  setter
}


测试类

//单向一对多保存时,一定会多出update语句,因为n端在插入时不会同时插入外键列
		@Test
		public void testOneToManyPersist() {
			Customer customer = new Customer();
			customer.setAge(23);
			customer.setEmail("[email protected]");
			customer.setLastName("shang");
			
			Order order1 = new Order();
			order1.setOrderName("订单1");
			
			Order order2 = new Order();
			order2.setOrderName("订单2");
			
			customer.getOrders().add(order1);
			customer.getOrders().add(order2);
			
			entityManager.persist(customer);
			entityManager.persist(order1);
			entityManager.persist(order2);
		}
		
		
		@Test
		public void testOneToManyFind() {
			Customer customer = entityManager.find(Customer.class, 1);
			System.out.println(customer.getLastName());
			System.out.println(customer.getOrders().size());//默认使用懒加载
		}
		
		@Test
		public void testOneToManyRemove() {
			Customer customer = entityManager.find(Customer.class, 1);
			entityManager.remove(customer);//默认order的外键被置为null,然后执行删除。设置cascade可以执行级联删除
		}
		
		//update操作
		@Test
		public void testOneToManyUpdate() {
			Customer customer = entityManager.find(Customer.class, 2);
			customer.getOrders().iterator().next().setOrderName("new name");
			
		}



不推荐这种关联方式








你可能感兴趣的:(email,private)