Bulk and batch operations The second HQL (JPA (Web design course)
Thursday, December 20th, 2007Bulk and batch operations The second HQL (JPA QL) bulk operation we introduce is the DELETE: Query q = session.createQuery( “delete CreditCard c where c.stolenOn is not null” ); int updatedCreditCards = q.executeUpdate(); The same rules as for UPDATE statements apply: no joins, single entity class only, optional aliases, subqueries allowed in the WHERE clause. Just like SQL bulk operations, HQL (and JPA QL) bulk operations don t affect the persistence context, they bypass any cache. Credit cards or items in memory aren t updated if you execute one of these examples. The last HQL bulk operation can create objects directly in the database. Creating new objects directly in the database Let s assume that all your customers Visa cards have been stolen. You write two bulk operations to mark the day they were stolen (well, the day you discovered the theft) and to remove the compromised credit-card data from your records. Because you work for a responsible company, you have to report the stolen credit cards to the authorities and affected customers. So, before you delete the records, you extract everything that was stolen and create a few hundred (or thousand) StolenCreditCard objects. This is a new class you write just for that purpose: public class StolenCreditCard { private Long id; private String type; private String number; private String expMonth; private String expYear; private String ownerFirstname; private String ownerLastname; private String ownerLogin; private String ownerEmailAddress; private Address ownerHomeAddress; … // Constructors, getter and setter methods } You now map this class to its own STOLEN_CREDIT_CARD table, either with an XML file or JPA annotations (you shouldn t have any problem doing this on your own). Next, you need a statement that executes directly in the database, retrieves all compromised credit cards, and creates new StolenCreditCard objects: Query q = session.createQuery( “insert into StolenCreditCard (type, number, expMonth, expYear,
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.