when I submit data using the commit method of DataContext, the submission fails because of the unique index of the database. At this time, the modifiedInstances in DataContext are not cleared and remain in DataContext. The next submission will lead to failure. Can we provide methods to clear these data or automatically clear them when exceptions occur?
for example, add a try… finally to the commit method, as follows:
@Override
public EntitySet commit() {
try{
PreCommitEvent preCommitEvent = new PreCommitEvent(this, modifiedInstances, removedInstances);
events.publish(PreCommitEvent.class, preCommitEvent);
if (preCommitEvent.isCommitPrevented())
return EntitySet.of(Collections.emptySet());
Set<Entity> committed = performCommit(preCommitEvent.getValidationMode(), preCommitEvent.getValidationGroups());
EntitySet committedAndMerged = mergeCommitted(committed);
events.publish(PostCommitEvent.class, new PostCommitEvent(this, committedAndMerged));
finally{
modifiedInstances.clear();
removedInstances.clear();
}
return committedAndMerged;
}
We should not clear modified instances collections on exception, because we need to give a chance to correct data and try to commit again.
Imagine that you have Order-OrderLines composition and the Order.number
attribute is unique. If you create an order with duplicated number, you will get an exception when clicking “OK”, but then you just correct the number, click “OK” again and all your entered data is saved. If we clear the lists after exception, we’ll lose the information about modifications and the user will have to enter all data again.
The key is that now after the exception occurs, it is impossible to get the entity that has made a specific exception, so it is impossible to tell the user which data to modify, only to erase it all. It’s OK if you can get the exact entity that went wrong in the exception, but you don’t know how to get it.
Could you provide a demo project where we can see the real problem?
I did this directly through reflection.