There are scenarios out there where you cannot use manual flush. For instance, long (application, user) persistence transaction or batch job utilizing facilities of the stateful session bean. Like this example of batch insertion job
Code:
@Stateful
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class InitBean implements Init {
@PersistenceContext(unitName = "titan", type = PersistenceContextType.EXTENDED)
private EntityManager manager;
@Spring(jndiName = "spring-pojo", bean = "statefulTravelService")
private TravelService travelService;
@PostConstruct
public void postConstruct() {
Assert.notNull(travelService, "Travel service is NULL!!!");
travelService.setManager(manager);
}
@Remove
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void flush() {
// syncrhonize with database;
}
public void initAirports(int index) {
logger.debug("initAirports() index " + index);
int size = getNumber(Airport.class);
if (size > 0) {
return;
}
String[] airports = new String[] { "Denver", "Hoover", "Chicago", "New York",
"San Francisco", "Cleveland", "Toronto", "Berlin",
"Washington", "Madison", "San Antonio", "Venice", "Rome",
"Istanbul", "Berlin", "Ottawa", "Vancoover", "Alamo", "London",
"Paris" };
List<Airport> lst = new ArrayList<Airport>();
for (int i = 0; i < index; i++) {
Airport port = new Airport();
int k = Util.createRandomInt(airports.length - 1);
String airport = airports[k];
port.setName(airport);
port.setAirportCode(airport.substring(0, 3).toUpperCase() + "_" + (i + 1));
lst.add(port);
}
travelService.createAirports(lst);
}
private int getNumber(Class clazz) {
return travelService.getNumberOfObjects(clazz);
}
}
You cannot put flush in your dao in this environment. So aspect catching and converting exception looks like a viable trick to me.
Cheers,
Arno