Java Reference
In-Depth Information
...
@Resource
private UserTransaction ut;
...
public String updateEmployeeStatusInactive {
try {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaUpdate<Employee> q = builder.createCriteriaUpdate(Employee.class);
Root<Employee> e = q.from(Employee.class);
q.set(e.get("status"), "INACTIVE")
.where(builder.equal(e.get("status"), "ACTIVE"));
ut.begin();
Query criteriaUpd = em.createQuery(q);
criteriaUpd.executeUpdate();
ut.commit();
} catch (NotSupportedException | RollbackException | SystemException |
HeuristicMixedException | HeuristicRollbackException ex) {
Logger.getLogger(CriteriaUpdates.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
...
The bulk deletion is very similar, except instead of using the CriteriaBuilder to obtain a CriteriaUpdate object,
use it to obtain a CriteriaDelete object instead. To obtain a CriteriaDelete object, call the CriteriaBuilder
createCriteriaDelete method, as follows.
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaDelete<Employee> q = builder.createCriteriaDelete(Employee.class);
Once a CriteriaDelete object has been obtained, then the conditions for deletion need to be specified by
filtering the results using a call (or chain of calls) to the .where method. When using the bulk delete, all objects that
match the specified condition will be deleted. For example, the following lines of code demonstrate how to delete all
Employee objects that have the status attribute equal to INACTIVE .
Root<Employee> e = q.from(Employee.class);
q.where(builder.equal(e.get("status"), "INACTIVE"));
The complete code for the bulk deletion in this example resides within a method named
deleteEmployeeOnStatus , which is listed below.
...
@Resource
private UserTransaction ut;
...
public String deleteEmployeeOnStatus(String condition) {
try {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaDelete<Employee> q = builder.createCriteriaDelete(Employee.class);
Root<Employee> e = q.from(Employee.class);
q.where(builder.equal(e.get("status"), condition));
ut.begin();
 
Search WWH ::




Custom Search