I'm trying to find a method that allows me to do a rollback when one of the elements of a list fails for a reason within the business rules established (ie: when throw my customize exception)
Example, (the idea is not recording anything if one element in list fails)
public class ControlSaveElement {
public void saveRecords(List<MyRecord> listRecords) {
Boolean status = true;
foreach(MyRecord element: listRecords) {
// Here is business rules
if(element.getStatus() == false) {
// something
status = false;
}
element.persist();
}
if(status == false) {
// I need to do roll back from all elements persisted before
}
}
...
}
Any idea? I'm working with Roo 1.2.2..
How about creating a new static method in the MyRecord entity:
@Transactional
public static void saveMyRecordsList(List<MyRecord> listRecords) {
boolean persistAll = true;
foreach(MyRecord element: listRecords) {
if(element.getStatus() == false) {
persistAll = false;
}
}
if (persistAll) {
foreach(MyRecord element: listRecords) {
entityManager().persist(element);
}
}
}
This may be more efficient than persisting elements and having to roll them back?