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,可還是報錯...求解,深表感謝!!
------解决思路----------------------
你用的junit测试,异常信息里的“session was closed”跟有没有开启“OpenSessionInViewFilter”没关系啊,“OpenSessionInViewFilter”只有通过网页访问的时候才起作用。所以问题很明显了,就是因为你用的spring管理的session,所以spring在查询完成后就把session关闭了。spring管理session的原则是:在哪里打开的,就在哪里关闭,不需要用户自己打开或者关闭。
------解决思路----------------------
要看事务边界,貌似是直接测试dao层,事务是不是放在service层?如果是,将测试类继承AbstractTransactionalJUnit4SpringContextTests,并在测试类上配置@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)和@Transactional。