I have an entity Simulation that can reference certain Model and entities are versioned using the Envers, strategy: ValidityAuditStrategy.
A Model can be independently updated, however, Simulation should keep referencing a certain version of the Model (which, most of the time is the newest, but don’t have to be).
Right now I implemented a soft link and loading the correct version of the Model using PostLoadEventListener. This approach works for me, however, it’s not the cleanest and not the fastest solution.
Could you recommend me a better approach? The ideal solution seems to be to reference the AUDIT table, but I do not think this is possible.
@Audited
public class Simulation {
Model model;
Integer modelVersion;
...
@ManyToOne(fetch = FetchType.LAZY) //Unidirectional
@JoinColumn(name = "MODEL")
public Model getModel() {
return model;
}
@Column(name = "modelVersion")
public Integer getModelVersion() {
return modelVersion;
}
...
}
public class OldLoadEventListener implements PostLoadEventListener{
static final OldLoadEventListener INSTANCE = new OldLoadEventListener();
@Override
@TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)
public void onPostLoad(PostLoadEvent event) {
final Object entity = event.getEntity();
Model model = ((GraphProcessStep) entity).getModel();
Integer modelVersion = ((GraphProcessStep) entity).getModelVersion();
final Model m = AuditReaderFactory.get(event.getSession()).createQuery()
.forRevisionsOfEntity(Model.class, true, true)
.add(AuditEntity.id().eq(model.getId()))
.add(AuditEntity.property("versionNumber").eq(modelVersion))
.getSingleResult();
model.setModel(m);
...
}
...
}