Thursday, October 30, 2014

JPA orphanRemoval=true VS CascadeType.REMOVE

A short comparison of  orphanRemoval and CascadeType.REMOVE properties.


CascadeType.REMOVE (and also CascadeType.ALL as a private case) tells the DB to delete all child records when the parent is deleted. That is if I delete the INVOICE, then delete all of the ITEMS on that INVOICE.


orphanRemoval=true tells the ORM that if I remove an Item object from the collection of Items that belong to an Invoice object (in memory operation), and then "save" the Invoice, the removed Item should be deleted from the underlying DB. In private case, the "collection" could be @OneToOne relationship, not just @OneToMany.

Source: some (not top rated ones!) of the comments in this stackoverflow thread.

Tuesday, October 14, 2014

Hibernate: Executing an update/delete query exception solved

If you get this exception:
nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query

It may be because you do not have @Transaction annotation in your repository class (interface). I tried adding @Transaction annotation to calling service or calling controller, but it did not solve the exception. If this do not help you, check step-by-step solution described in this stackoverflow thread.

Monday, October 13, 2014

Hibernate - delete query example

Delete query by parent. Annotation approach used and this code is placed in repository class (interface):
    @Query("DELETE FROM Child WHERE parent = :parent")
    public void deleteAllForParent( @Param("parent") Parent parent );

Child class has field named parent.