建议在一多对关联中在"一"方用延迟加载"多"方
可以在HQL中显式的"迫切左外连接" left join fetch
这样做Hibernate可以少访问数据库,也可以用"@BatchSize(size = 5)"来减少访问数据库的次数
User.java 一方
@Entity
@Table(name = "tbl_user")
@org.hibernate.annotations.Entity(dynamicUpdate=true,dynamicInsert=true)
public class User implements Serializable{
@Id
@GeneratedValue(generator="gen")
@GenericGenerator(name="gen",strategy="increment")
@Column(name="id")
private Integer id;
/**
* username
*/
@Column(name="username", length=50, insertable = true, updatable = true, nullable = false)
private String username;
/**
* password
*/
@Column(name="password", length=20, insertable = true, updatable = true, nullable = false)
private String password;
/**
* 创建时间
*/
@Column(name="createtime")
@Temporal(value=TemporalType.TIMESTAMP)
private Date createtime;
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy = "user")
@BatchSize(size = 5)
private Set<Order> orders=new HashSet<Order>();
/**
* 省略get,set方法
*/
}
Order.java 多方
@Entity
@Table(name = "tbl_order")
@org.hibernate.annotations.Entity(dynamicUpdate=true,dynamicInsert=true)
public class Order implements Serializable{
/**
* id
*/
@Id
@GeneratedValue(generator="gen")
@GenericGenerator(name="gen",strategy="increment")
@Column(name="id")
private Integer id;
/**
* orderNum
*/
@Column(name="orderNum", length=50, insertable = true, updatable = true, nullable = false)
private String orderNum;
/**
* 创建时间
*/
@Column(name="createtime")
@Temporal(value=TemporalType.TIMESTAMP)
private Date createtime;
@ManyToOne
@JoinColumn(name = "userId")
private User user;
/**
* 省略get,set方法
*/
}
UseerDaoImpl.java中部分代码
public List<User> listUser(){
List<User> list=this.getHibernateTemplate().find(" from User as u left join fetch u.orders ");
return list;
}