spirng 配置文件 applicationContext.xml
//省略一大段
<!-- 开启扫描 -->
<!-- 重要配置:启用扫描并自动创建代理的功能 -->
<jpa:repositories base-package="me.zonghua.sync.repository"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory" />
<!-- 开启注解事务 -->
<!-- <tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />
<aop:aspectj-autoproxy /> -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- <aop:config> <aop:pointcut id="txPointcut" expression="execution(*
me.zonghua..service.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"
/> </aop:config> -->
TopicServ.java
@Transactional
public Page<Topic> getTopicsByType(String type,int page,int size){
String properties="content";
Pageable pageRequest=new PageRequest(--page, size, Sort.Direction.DESC, properties);
Page<Topic> topicPage= topicRepo.findAll(pageRequest);
for(Topic topic:topicPage.getContent()){
User lastCommentUser = userRepo.getLastCommentUserByTopicId(topic.getId());
if(lastCommentUser!=null){
topic.setLastCommentUser(lastCommentUser);
}
Comment lastComment=commentRepo.getLastCommentByTopicId(topic.getId());
if(lastComment!=null){
topic.setLastCommentAt(lastComment.getCreateAt());
}
}
return topicPage;
}
junit
//只有在junit里面加了 @Transactional 才有会话
@Test
public void get(){
Page<Topic> topicPage=t.getTopicsByType("", 1, 10);
topicPage.getContent().get(0).getUser().getUsername();
}
否则就会报错,没有会话
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at me.zonghua.sync.entity.User_$$_jvstc0d_9.getAvatar(User_$$_jvstc0d_9.java)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:97)
at org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:110)
at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:943)
看一下事务注解配置有什么问题?
页面上进行多对一或者一对一取值的时候要懒加载或者用过滤器吧会话延长到视图渲染时期
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于