1、 问题描述
有如下实体
Classify(分类):
@Entity
public classClassify {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer classifyId;
private String classifyName;
private Integer classifyParentId;
public Integer getClassifyId(){
return classifyId;
}
public void setClassifyId(IntegerclassifyId) {
this.classifyId = classifyId;
}
public StringgetClassifyName() {
return classifyName;
}
public void setClassifyName(StringclassifyName) {
this.classifyName = classifyName;
}
public IntegergetClassifyParentId() {
return classifyParentId;
}
public voidsetClassifyParentId(Integer classifyParentId) {
this.classifyParentId = classifyParentId;
}
}
Note(笔记):
@Entity
public classNote {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer noteId;
private String noteTime;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="classifyId")
private Classify classify;
private String keywords;
private String noteName;
private String noteContent;
private String noteSummary;
}
Note与Classify的关系是:多对一的关系
在DAO中分页查询Note
return getHibernateTemplate().execute(newHibernateCallback<Page<Note>>() {
@Override
publicPage<Note> doInHibernate(Session session)
throwsHibernateException, SQLException {
Criteriacriteria = detachedCriteria.getExecutableCriteria(session);
longtotalSize = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
criteria.setProjection(null);
criteria.setFirstResult((query.getPageNo()- 1) * query.getPageSize());
criteria.setMaxResults(query.getPageSize());
List<Note> dataList =criteria.list();
for(Note note : dataList) {
note.getClassify().getClassifyName();
}
returnnew Page<Note>(query.getPageSize(), query.getPageNo(), totalSize,dataList);
}
});
Debug发现查询到的dataList为
原因是因为查找Note的时候也会将关联的Classify查找出来,如果改成延迟加载,那么不会查找出对象数组,暂时没有找到根本的解决方法,暂时的解决方法如下:
1、 改为延迟加载
2、 将关联的对象显式的加载出来
for(Note note : dataList) {
note.getClassify().getClassifyName();
}