gpt4 book ai didi

spring - Jpa + Spring - 从数据库读取后自动设置 transient 字段值

转载 作者:行者123 更新时间:2023-12-04 14:59:39 26 4
gpt4 key购买 nike

从数据源读取实体后,为标记为@Transient 的字段设置值的最佳解决方案是什么?

我正在使用 EclipseLink 并且我正在尝试使用他的 postBuild 事件解决方案的 DescriptorEventAdapter 因为我还需要使用 Spring bean 获取默认值(显然使用 DI),但我想知道是否有任何更简单的解决方案丢失的。

提前致谢

最佳答案

如果您使用的是存储库或 DAO,这是一种简单的方法:

@Repository
class YourRepository {

@Autowired
private Bean bean;

@PersistenceContext
private EntityManager entityManager;

@Transactional(readOnly = true)
public YourEntity find(..) {
YourEntity entity = lookupUsingEntityManager();
entity.transientField = bean.getDefaultValue();
return entity;
}
}

如果您使用事件记录样式的实体,这是另一种方法:
@Entity
class YourEntity {

@Transient
public Object field;

@PostLoad
public void populateField() {
field = new BeanHolder().bean.getDefaultValueForField();
}

@Configurable
private static class BeanHolder {
@Autowired private Bean bean;
}
}

注意半伪代码。请注意,后一种方法仅在您使用 <context:spring-configured /> 使用编译时或加载时 AspectJ 编织时才有效。 .

关于spring - Jpa + Spring - 从数据库读取后自动设置 transient 字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18536930/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com