web.xml
[code="java"]
OpenSessionInViewFilter
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
sessionFactoryBeanName
SessionFactory
singleSession
true
OpenSessionInViewFilter
/*
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
[/code]
映射:
[code="java"]
index
[/code]
DAO:
[code="java"]
public BulletinIndex findIndexById(String id){
return (BulletinIndex) sessionFactory.getCurrentSession().load(BulletinIndex.class, id);
};
[/code]
看了不少博文,问题没有解决。如果不用load而直接写一个不带关联对象的查询不会报错,但执行出来的时候hibernate会添加上另一个关联对象的查询。
你这是在单元测试啊,单元测试的话
OpenSessionInViewFilter不起作用
也就是说session用完一次就自动 关闭了,并不能保证像WEB那样直到请求结束才关闭
你的级联加载策略又是慢加载
所以就报空了
如果lazy="proxy"改成
lazy="false"
应该是没问题 的
你把错误堆栈打出来看看
[quote]看了不少博文,问题没有解决。如果不用load而直接写一个不带关联对象的查询不会报错,但执行出来的时候hibernate会添加上另一个关联对象的查询。[/quote]
这没理解~~~ :x
[quote]如果不用load而直接写一个不带关联对象的查询不会报错,但执行出来的时候hibernate会添加上另一个关联对象的查询。
[/quote]
这话没理解
写一个不带关联对像的查询不会报错,
那自动 添加的另一个关联对像查询是哪里的对像?
可以的,看你怎么用那个SESSION了
[code="java"]在单元测试中测试延迟加载
需要用 J-Unit 来测试我们的延迟加载程序。我们可以轻易地通过重写 TestCase 类中的 setUp 和 tearDown 方法来实现这个要求。
1. import junit.framework.TestCase;
2. import org.hibernate.Session;
3. import org.hibernate.SessionFactory;
4. import org.springframework.orm.hibernate3.SessionFactoryUtils;
5. import org.springframework.orm.hibernate3.SessionHolder;
6. import org.springframework.transaction.support.TransactionSynchronizationManager;
7. public abstract class MyLazyTestCase extends TestCase {
8. private SessionFactory sessionFactory;
9. private Session session;
10. public void setUp() throws Exception {
11. super.setUp();
12. SessionFactory sessionFactory =
13. (SessionFactory) getBean("sessionFactory");
14. session = SessionFactoryUtils.getSession(sessionFactory, true);
15. Session s = sessionFactory.openSession();
16. TransactionSynchronizationManager.bindResource(sessionFactory,
new SessionHolder(s));
17. }
18. protected Object getBean(String beanName) {
19. //Code to get objects from Spring application context
20. return null;
21. }
22. public void tearDown() throws Exception {
23. super.tearDown();
24. SessionHolder holder =
(SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
25. Session s = holder.getSession();
26. s.flush();
27. TransactionSynchronizationManager.unbindResource(sessionFactory);
28. SessionFactoryUtils.closeSession(s);
29. }
30. }
[/code]
能看看你的单元测试的那个类的完整代码吗?
OpenSessionInViewFilter
在单元测试里是没用的
[quote]System.out.println("start");
SessionFactory sf = null;
Session s = null;
sf = (SessionFactory) ctx.getBean("sessionFactory");
s = sf.openSession();
Transaction tran = s.getTransaction();
tran.begin();
BulletinIndex index = (BulletinIndex) s.createQuery("from BulletinIndex where id=:id").setString("id", "BD16B5FFD03940BDA9E01C5E893DC07D").uniqueResult();
System.out.println(index.getTitle());
tran.commit();
s.close();
sf.close(); [/quote]
这个执行了两条SQL?
你把lazy设置成true,不要proxy