开发者社区> 问答> 正文

spring-boot jpa二级缓存以及懒加载问题!:配置报错 

我使用的是spring-boot应用框架,目前碰到2个问题。
1:缓存问题:目前是将hibernate作为Jpa的实现框架,cache的实现是ehcache,在application.properties里面配置了如下:

在最下一行,sharedCache处,现在是等于ALL,文档说是加入这个后,则不需要在entity加入@Cacheable就可以开启全局缓存,但是无论加还是没加(org.springframework.cache.annotation.Cacheable)或者是(javax.persistence.Cacheable;)都无效,我的调用方式是在junit中这样写的

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ProductTest {

	@Inject
	private ProductService productService;

	@Test
	public void testOrder() throws Exception {

		System.out.println(productService.find_by_id(1));
		
	}
	@Test
	public void testkk() throws Exception {

		System.out.println(productService.find_by_id(1));
		System.out.println(productService.find_by_id(1));
		System.out.println(productService.find_by_id(1));
	}
}
但最后确发送了4条SQL语句,显然是没有缓存。同时缓存日志也没有用
hibernate.generate_statistics=true

问题2:延迟加载
在做ORM的时候,不管是1对多还是多对1,必须要使用

FetchType.EAGER

才不会出session closed的错误,可是我想用orm的二级缓存,就是想要出现N+1,但如果我使用这种配置,就会将子表一并查出,而不是我想要的单表的ID查询

可如果改成

FetchType.LAZY

就会出session closed的问题,网络上有那种在web.xml配置

OpenEntityManagerInViewFilter

可是,spring-boot没有web.xml,所以我就无从下手了,或者有其他的方法可以解决,谢谢各位了

展开
收起
kun坤 2020-05-31 23:02:39 514 0
1 条回答
写回答
取消 提交回答
  • @org.hibernate.annotations.Cache()
    使用这个注解试试,如果你的controller使用了@Cacheable,那么OpenInViewFilter是没有用的,他对缓存结果没有控制,spring boot 默认是开启了这个filter,具体看jpa相关配置

    ######.请问下..楼主的问题解决了嘛?######

    引用来自“HelloBox”的评论

    .请问下..楼主的问题解决了嘛? 你说的是哪个问题######

    引用来自“HelloBox”的评论

    .请问下..楼主的问题解决了嘛?

    引用来自“ramus”的评论

    你说的是哪个问题 那个懒加载的问题######
    在WebAppInitializer重写
    
    onStartup()方法 加上
    
    FilterRegistration.Dynamic dynamic =   servletContext.addFilter("openEntityManagerInViewFilter"  ,org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.class);
     dynamic.addMappingForUrlPatterns(null,false,"/*");
    2020-05-31 23:02:48
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
云栖社区特邀专家徐雷Java Spring Boot开发实战系列课程(第20讲):经典面试题与阿里等名企内部招聘求职面试技巧 立即下载
微服务架构模式与原理Spring Cloud开发实战 立即下载
阿里特邀专家徐雷Java Spring Boot开发实战系列课程(第18讲):制作Java Docker镜像与推送到DockerHub和阿里云Docker仓库 立即下载

相关实验场景

更多