Reputation: 1002
what's the best solution to set a value for a field marked @Transient after the entity has been read from the data source?
I'm using EclipseLink and I'm trying the DescriptorEventAdapter with his postBuild event solution because I need also to get the default value using a Spring bean (obviuosly using DI), but I would know if there is any simpler solution that I'm missing.
Thanks in advance
Upvotes: 6
Views: 6653
Reputation: 4663
Here's the simple approach if you're using a repository or 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;
}
}
Here's another approach if you are using active record -style entities:
@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;
}
}
Mind the semi-pseudo-code. Note that the latter approach works only if you use compile- or load-time AspectJ weaving with <context:spring-configured />
.
Upvotes: 6
Reputation: 1117
You got entity which has transient field and the value is always taken from service using DI?
Note that entity and service has completely different lifecycle. The value is changing in the time so it does not make the sense to supply the value in entity's factory at the beginning of it's life?
Upvotes: 0