Last active
April 26, 2017 08:07
-
-
Save thjanssen/0f6ab558b885f87d6e70 to your computer and use it in GitHub Desktop.
Criteria Update/Delete - The easy way to implement bulk operations with JPA2.1 (http://www.thoughts-on-java.org/2013/10/criteria-updatedelete-easy-way-to.html)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Stateless | |
@LocalBean | |
public class OrderManagement { | |
@PersistenceContext | |
private EntityManager em; | |
... | |
public void deleteOrder(Double amount) { | |
CriteriaBuilder cb = this.em.getCriteriaBuilder(); | |
// create delete | |
CriteriaDelete<Order> delete = cb. | |
createCriteriaDelete(Order.class); | |
// set the root class | |
Root e = delete.from(Order.class); | |
// set where clause | |
delete.where(cb.lessThanOrEqualTo(e.get("amount"), amount)); | |
// perform update | |
this.em.createQuery(delete).executeUpdate(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Stateless | |
@LocalBean | |
public class OrderManagement { | |
@PersistenceContext | |
private EntityManager em; | |
... | |
public void updateOrder(Double oldAmount, Double newAmount) { | |
CriteriaBuilder cb = this.em.getCriteriaBuilder(); | |
// create update | |
CriteriaUpdate<Order> update = cb. | |
createCriteriaUpdate(Order.class); | |
// set the root class | |
Root e = update.from(Order.class); | |
// set update and where clause | |
update.set("amount", newAmount); | |
update.where(cb.greaterThanOrEqualTo(e.get("amount"), oldAmount)); | |
// perform update | |
this.em.createQuery(update).executeUpdate(); | |
} | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment