Jpa + Spring - 从DB读取后自动设置瞬态字段值

lin*_*tto 6 spring jpa transient eclipselink spring-data-jpa

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

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

提前致谢

Juk*_*kka 6

如果您使用的是存储库或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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用活动记录样式实体,这是另一种方法:

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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