JPA Select latest instance for each item

In SQL the solution is very simple – join the table with a subquery, which gives you the most recent meeting for each attendee: select * from Meeting ALL join ( select max(meetingDate) as newest, attendee from Meeting group by attendee ) LATEST on ALL.meetingDate = LATEST.newest AND ALL.attendee = LATEST.attendee This works, and works … Read more

SpringBoot doesn’t handle org.hibernate.exception.ConstraintViolationException

You cannot catch ConstraintViolationException.class because it’s not propagated to that layer of your code, it’s caught by the lower layers, wrapped and rethrown under another type. So that the exception that hits your web layer is not a ConstraintViolationException. In my case, it’s a TransactionSystemException. I’m using @Transactional annotations from Spring with the JpaTransactionManager. The … Read more

Spring Data JPA: How can Query return Non- Entities Objects or List of Objects?

You can do something like @NamedQuery(name=”findWhatever”, query=”SELECT new path.to.dto.MyDto(e.id, e.otherProperty) FROM Student e WHERE e.id = ?1″) Then the MyDto object would just need a constructor defined with the correct fields i.e. public MyDto(String id, String otherProperty) { this.id = id; this.otherProperty = otherProperty; }

Really dynamic JPA CriteriaBuilder

You can pass an array of predicates to the CriteriaBuilder, deciding on equal or like as you go. For this, build a list and pack the contents of the list into an array in a single and statement. Like this: final List<Predicate> predicates = new ArrayList<Predicate>(); for (final Entry<String, String> e : myPredicateMap.entrySet()) { final … Read more

How to use JPA2’s @Cacheable instead of Hibernate’s @Cache

According to the JPA 2.0 specification, if you want to selectively cache entities using the @Cacheable annotation, you’re supposed to specify a <shared-cache-mode> in the persistence.xml (or the equivalent javax.persistence.sharedCache.mode when creating the EntityManagerFactory). Below, a sample persistence.xml with the relevant element and properties: <persistence xmlns=”http://java.sun.com/xml/ns/persistence” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd” version=”2.0″> <persistence-unit name=”FooPu” transaction-type=”RESOURCE_LOCAL”> <provider>org.hibernate.ejb.HibernatePersistence</provider> … … Read more