- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
使用redis作为spring cache,从redis获取对象时异常。json数据保存到redis如下
{"@class":"cc.giveme5.auth.RoleEntity","id":10001,"name":"member","description":"注册用户","type":1,"permissions":["org.hibernate.collection.internal.PersistentSet",[{"@class":"cc.giveme5.auth.PermissionEntity","id":10001,"name":"member:read","description":"注册用户访问许可"}]]}
## env
spring-boot: 2.0.2.RELEASE
spring-data-redis: 2.0.7.RELEASE
jackson: 2.9.5
hibernate: 5.0.1
Spring Boot 默认注册 OpenEntityManagerInViewInterceptor 以在 spring-boot(2.0.2.RELEAS) 中应用“Open EntityManager in View”模式。
@Entity
@Table(name = "t_auth_role_m")
@JsonIgnoreProperties(ignoreUnknown = true)
public class RoleEntity implements Serializable
{
@Id
@TableGenerator(name = "UrRole_gen", table = "t_com_id_generator_r", pkColumnName = "seq_name", pkColumnValue = "UrRole_id", valueColumnName = "seq_value", allocationSize = Constants.SQE_ALLOCATION)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "UrRole_gen")
private Long id;
private String name;
private String description;
/**
* 角色对应许可
*/
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "t_auth_role_perm_r",
joinColumns = { @JoinColumn(name = "role_id", referencedColumnName = "id") },
inverseJoinColumns = { @JoinColumn(name = "perm_id", referencedColumnName = "id") })
private Set<PermissionEntity> permissions;
}
@Entity
@Table(name = "t_auth_perm_m")
@JsonIgnoreProperties(ignoreUnknown=true)
public class PermissionEntity implements Serializable {
@Id
private Long id;
@Column(length = 32, name = "perm_name", nullable = false)
@Size(max = 32)
private String name;
@Column(length = 128, name = "perm_description", nullable = false)
@Size(max = 128)
private String description;
}
@Configuration
@EnableCaching
public class CacheConfiguration {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
@ConfigurationProperties(prefix = "giveme5.cache")
public Properties4Cache cacheProperties(){
return new Properties4Cache();
}
@Bean
@Primary
public CompositeCacheManager cacheManager(){
CompositeCacheManager cacheManager = new CompositeCacheManager();
ArrayList<CacheManager> cacheManagers = new ArrayList<>();
//cacheManagers.add(simpleCacheManager());
cacheManagers.add(redisCacheManager(new redisObjectMapper(), redisConnectionFactory));
cacheManager.setCacheManagers(cacheManagers);
cacheManager.setFallbackToNoOpCache(true);
return cacheManager;
}
@Bean
public RedisCacheManager redisCacheManager(ObjectMapper objectMapper, RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(cacheProperties().getRedisCacheTtl()))
.computePrefixWith(cacheName -> cacheProperties().getName().concat(":").concat(cacheName).concat(":"))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer(objectMapper)))
;
RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(cacheConfiguration)
.build();
cacheManager.setTransactionAware(true);
return cacheManager;
}
public class redisObjectMapper extends ObjectMapper {
public redisObjectMapper() {
super();
// 将类型序列化到属性json字符串中
this.enableDefaultTyping(DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
this.registerModule(new Hibernate5Module().disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION));
// 对于找不到匹配属性的时候忽略报错
this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 不包含任何属性的bean也不报错
this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
}
}
@Service
@Transactional
public class RoleService {
@Autowired
private IRoleRepository roleRepository;
@Cacheable(cacheNames = "default", key = "'role.' + #p0")
public RoleEntity role(Long roleId) {
return roleRepository.getOne(roleId);
}
}
public interface IRoleRepository extends BaseRepository<RoleEntity, Long, BaseVO> {
}
服务中发生错误:
org.springframework.data.redis.serializer.SerializationException: Could not read JSON: failed to lazily initialize a collection, could not initialize proxy - no Session (through reference chain: cc.giveme5.auth.RoleEntity["permissions"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection, could not initialize proxy - no Session (through reference chain: cc.giveme5.auth.RoleEntity["permissions"])
at org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer.deserialize(GenericJackson2JsonRedisSerializer.java:132) ~[spring-data-redis-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer.deserialize(GenericJackson2JsonRedisSerializer.java:110) ~[spring-data-redis-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.data.redis.serializer.DefaultRedisElementReader.read(DefaultRedisElementReader.java:50) ~[spring-data-redis-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.data.redis.serializer.RedisSerializationContext$SerializationPair.read(RedisSerializationContext.java:204)
...
Caused by: com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection, could not initialize proxy - no Session (through reference chain: cc.giveme5.auth.RoleEntity["permissions"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:391) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:351) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.wrapAndThrow(BeanDeserializerBase.java:1704) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:290) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:189) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:161) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer._deserializeTypedForId(AsPropertyTypeDeserializer.java:130) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:97) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromAny(AsPropertyTypeDeserializer.java:193) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer$Vanilla.deserializeWithType(UntypedObjectDeserializer.java:712) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:68) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4001) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3079) ~[jackson-databind-2.9.5.jar:2.9.5]
at org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer.deserialize(GenericJackson2JsonRedisSerializer.java:130) ~[spring-data-redis-2.0.7.RELEASE.jar:2.0.7.RELEASE]
... 96 common frames omitted
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:582) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:201) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:145) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.collection.internal.PersistentSet.size(PersistentSet.java:143) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:302) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:245) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:27) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer._deserialize(AsArrayTypeDeserializer.java:116) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer.deserializeTypedFromArray(AsArrayTypeDeserializer.java:53) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserializeWithType(CollectionDeserializer.java:314) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129) ~[jackson-databind-2.9.5.jar:2.9.5]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288) ~[jackson-databind-2.9.5.jar:2.9.5]
... 106 common frames omitted
最佳答案
你好。当你调用它时,Hibernate 会初始化惰性属性,所以 permissions 不会在加载 RoleEntity 时初始化。hibernate 加载根对象后,第一次调用permissions 时,hibernate 从数据库中获取数据并加载permissions 属性。为了启动惰性属性,hibernate 需要一个有效的 session 。如果关闭 hibernate session ,则对象分离并且无法初始化惰性属性并引发 LazyInitializationException为了解决你可以使用:1- 设置获取类型加入。在一个选择语句中加载具有根对象的属性。2- 在关闭 session 之前,调用permissions 属性进行启动。3- 实现从 RoleEntity 对象加载 permissions 属性的方法。
这有用吗?
阿亚提
关于java - spring cache redis : LazyInitializationException failed to lazily initialize a collection, 无法初始化代理 - 无 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51225063/
我开始学习使用 Hibernate 来开发 Java 中的 Web 系统,但我在类的映射和使用方面遇到了一些问题。 我有两个表:tblusuario和tblperfilusuario,tblusuar
我正在开发一个部署在 Tomcat 上的 J2EE 服务器应用程序。我使用 Spring 源作为 MVC 框架,使用 Hibernate 作为 ORM 提供者。我的对象模型有很多惰性关系(根据请求获取
我在尝试访问 permissions 时遇到 LazyInitializationException我的 Collection User目的。异常信息: org.hibernate.LazyIniti
我在我们的生产网络服务器上收到以下错误: NHibernate.LazyInitializationException : Initializing[Domain.Entities.AudienceT
这是一个让我困惑的问题。我正在尝试实现基本的 Hibernate DAO 结构,但遇到了问题。 这是基本代码: int startingCount = sfdao.count(); sfdao.cre
我看到类似的问题已经发布过,但是标准建议的解决方案似乎不适用于我,我想了解原因。 我有一个非常活跃的Grails 2.2.5应用程序,而且我一直在调查涉及大量数据集的报告问题。所讨论的域类是Polic
嗨,我有使用 jhipster 4.2.0 的微服务应用程序这是我的资源类 import org.springframework.web.bind.annotation.*; import javax
我有一个 Patient 类,其中包含 Id 集合和文件夹集合。当我尝试单独保存文件夹时,由于患者的 id 集合,它会抛出 LazyInitializationException。 患者类别如下所示:
我正在使用 Hibernate 3.6.0 制作一个应用程序,但出现了 LazyInitializationException。我没能解决这个问题,所以我来这里寻求你的帮助。 这是堆栈跟踪: Exce
在将域对象从数据库转换为客户端的资源对象期间,我遇到延迟加载字段的问题。 Customer :使用惰性字段从数据库加载实体 FullCustomer :将发送给客户端的实体。 服务层: @Transa
我有一个问题。我在 grails 中有事务性服务: class MyService { static transactional = true Set getFurniture(Long
我有一些具有两种关系的模型: @Entity @Table(name = "data_model") public class DataModel { @Id @GeneratedVa
传统上,我们会尝试避免 LazyInitializationException。但是,我需要暂时允许它们被抛出。这是我想要做的伪代码: Session session = ...; Customer
我正在将 Hibernate 4 用于 Java 项目。 我有下一个包含两个实体的方案: Units *has many* Users 因此,单位拥有用户的外键(请参阅 table definitio
JPA session 在静态方法中的行为如何?我使用 Hibernate 从数据库中检索对象列表,然后使用 Guava 的静态 Lists.transform 方法对其进行转换,这会导致: org.
我有这样的 OmQcActivity 类: @Entity @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @Table(name="OM_QC
我的代码运行良好,但出现异常。将调用一个操作方法,但是在方法调用完成后我得到了这个异常。 我尝试了网络上所有可用的选项,但似乎没有什么能真正帮到我。 12/14 23:30:17 INFO er.S
目前我有一个子实体有一个 @ManyToOne关联到它的父实体。之前的开发者已经将这个字段设置为 lazy="false"在 session 关闭时也可以随时获取父级,但我决定它应该是 lazy="t
此代码的目的是允许用户检查 ID;在这种情况下,它将是检查特定运动比赛的 ID,以便查看相关比赛及其详细信息。这样做的全部目的是通知用户,如果他们输入了错误的 ID,我只是想在 SOAP 请求中生成一
尝试从数据库获取某些对象时,我不断收到错误: org.hibernate.LazyInitializationException (LazyInitializationException.java:1
我是一名优秀的程序员,十分优秀!