Hibernate4之一对多双向关联

一个用户可以有多个订单,订单相对于用户的关系就是多对一的关系。
在这里一对多的关系是@OneToMany,默认是延迟加载的。当然客户对象相对于订单是级联删除的。

/**
 * @author Chou
 * @since 2012-8-8
 * ...客户实体(一对多双向关联)
 *
 */

@Entity
@Table(name = "TAB_CUSTOMER")
@SequenceGenerator(name = "seq", sequenceName = "SEQ_CUSTOMER", allocationSize = 1)
public class Customer {
	private Long id;
	private String cname;
	private String address;
	private String phone;
	private Set<Order> orders = new HashSet<Order>();
	
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
	public Long getId() {
		return id;
	}
	
	......
	
	@OneToMany(mappedBy = "customer", fetch = FetchType.EAGER,cascade = CascadeType.REMOVE)
	//@Fetch(value = FetchMode.JOIN)
	public Set<Order> getOrders() {
		return orders;
	}

	public void setOrders(Set<Order> orders) {
		this.orders = orders;
	}

}


/**
 * @author Chou
 * @since 2012-8-8
 * ...订单实体
 *
 */

@Entity
@Table(name = "TAB_ORDER")
@SequenceGenerator(name = "seq", sequenceName = "SEQ_ORDER", allocationSize = 1)
public class Order {
	private Long id;
	private String orderno;
	private Double money;
	private Customer customer;
	
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
	public Long getId() {
		return id;
	}
        
        ......
	
	@ManyToOne
	@Cascade(value = { org.hibernate.annotations.CascadeType.SAVE_UPDATE })
	@JoinColumn(name = "CUSTOMERID")
	public Customer getCustomer() {
		return customer;
	}
	public void setCustomer(Customer customer) {
		this.customer = customer;
	}
}

你可能感兴趣的:(Hibernate,jpa,多对一双向)