one获取数据时默认是不主动获取many的
one简单代码:
public class Subject implements Serializable{
private Set<Reply> replys = new HashSet<Reply>();
//get set…
@OneToMany(mappedBy = “subject”, targetEntity = Reply.class, cascade = {
CascadeType.PERSIST, CascadeType.REFRESH,CascadeType.REMOVE})
public Set<Reply> getReplys() {
return replys;
}
}
many简单代码:
public class Reply implements Serializable{
private Subject subject;
//get set…
@ManyToOne
@JoinColumn(name=”subject_id”,nullable=false)
public Subject getSubject() {
return subject;
}
}
test代码:
@Test
public void testGetReply() {
act = new ClassPathXmlApplicationContext(“beans.xml”);
SubjectDao subjectDao = (SubjectDao) act.getBean(“subjectDaoImpl”);
[color=#000080] Subject subject = subjectDao.get(1);
// 對應的get 方法代碼 return (Subject) getHibernateTemplate().get(Subject.class, id);
Set<Reply> replys = subject.getReplys();
//在這里就報錯了,
System.out.println(replys);[/color]
/* Iterator<Reply> replyIt = replys.iterator();
while(replyIt.hasNext()){
Reply reply = replyIt.next();
System.out.println(reply);
reply.getContent();
reply.getDate();
}*/
}
[color=#000000]org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: cc.blogs.domain.Subject.replys, no session or session was closed[/color]
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:365)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:108)
at org.hibernate.collection.PersistentSet.toString(PersistentSet.java:332)
at java.lang.String.valueOf(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at cc.blogs.junit.SubjectDaoTest.testGetReply(SubjectDaoTest.java:43)
……………………………………………………………
有什麽辦法獲取many 而又 不設置 one获取数据时主动获取many,
我試了下設置:OpenSessionInViewFilter,可還是報錯…求解,深表感謝!