Java Magazine, March/April 2016
ORACLE COM JAVAMAGAZINE MARCH APRIL 2016 51 enterprise java Bulk updates In some instances it makes sense to apply an update to a large number of database records Perhaps you need to update the cost for all customers in a particular city due to material increases or maybe all customers with a specific pool style need to be updated to enable or disable maintenance due status In the following example I use the latter scenario so that all customers of a specified pool type will have maintenance either enabled or disabled when the update is executed To perform a bulk update use a CriteriaBuilder to generate a CriteriaUpdate object that is set to the type of entity you want to update In the following example I want to update the Customer entity so I call the Criteria Builder createCriteriaUpdate method passing it the Customer class CriteriaUpdate Customer customerUpdate builder createCriteriaUpdate Customer class The CriteriaUpdate object can then be used to indicate which field s of the entity will be updated and under which conditions the update will occur In the following example I am using a Join Customer Pool object identified as poolCustomers to retrieve the style of pool that each customer owns Therefore I call the CriteriaUpdate set method passing the path expression to the fields I want to update along with the values to set Next I call the where method which specifies the conditions under which the update is applied Once again I can use the builder pattern customerUpdate set customer get Customer_ currentMaintenance enabled where builder equal poolCustomers get Pool_ style poolStyle Once all of the appropriate fields have been set and conditions have been put into place I create a Query object by calling the EntityManager createQuery method and passing the customerUpdate Query q em createQuery customerUpdate Lastly I invoke the executeUpdate method to execute the update The complete listing for this bulk update example is shown in Listing 8 Listing 8 public void updateMaintenanceByPoolType String poolStyle boolean enabled CriteriaBuilder builder em getCriteriaBuilder CriteriaUpdate Customer customerUpdate builder createCriteriaUpdate Customer class Root Customer customer customerUpdate from Customer class Join Customer Pool poolCustomers customer join Customer_ pool customerUpdate set customer get Customer_ currentMaintenance enabled where builder equal poolCustomers get Pool_ style poolStyle Query q em createQuery customerUpdate q executeUpdate em flush
You must have JavaScript enabled to view digital editions.