Spring Boot + JPA + Redis Cache + LazyInitializationException

时间:2017-06-17 05:18:40

标签: java spring jpa spring-boot redis

1)我使用spring-boot 1.5.3,jpa.redis作为缓存提供程序

@Override
@Cacheable(value = "product",key = "#id")
@Transactional(readOnly = true)
public Product getOne(long id) {
    return repository.findOne(id);
}

这是实体attr:

 @OneToMany(mappedBy = "product", fetch = FetchType.LAZY,cascade =CascadeType.ALL, orphanRemoval = true)
 private List<ProductAttr> productAttrs;

2)当我从redis缓存中获取产品时,抛出org.hibernate.LazyInitializationException。

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.xx.domain.product.Product.productAttrs, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:587) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:204) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:566) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.collection.internal.PersistentBag.clear(PersistentBag.java:381) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]

但我使用jcache是​​ok.i debuged并发现PersistentBag抛出LazyInitializationException。 如何解决?

3,这是我的RedisCacheConfig

  @Value(value = "${spring.redis.host}")
    private String hostName;

@Value(value = "${spring.redis.port}")
private String port;

@Bean
JedisConnectionFactory jedisConnectionFactory() {
    JedisConnectionFactory factory = new JedisConnectionFactory();
    factory.setHostName(hostName);
    factory.setPort(Integer.parseInt(port));
    factory.setUsePool(true);
    return factory;
}

@Bean
RedisTemplate<Object, Object> redisTemplate() {
    RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
    redisTemplate.setConnectionFactory(jedisConnectionFactory());
    return redisTemplate;
}

@Bean
public CacheManager cacheManager() {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate());
    cacheManager.setTransactionAware(true);
    cacheManager.setLoadRemoteCachesOnStartup(true);
    cacheManager.setUsePrefix(true);
    return cacheManager;
}

0 个答案:

没有答案