Spring Data JPA map the native query result to Non-Entity POJO

I think the easiest way to do that is to use so called projection. It can map query results to interfaces. Using SqlResultSetMapping is inconvienient and makes your code ugly :). An example right from spring data JPA source code: public interface UserRepository extends JpaRepository<User, Integer> { @Query(value = “SELECT firstname, lastname FROM SD_User WHERE … Read more

Spring Boot, Spring Data JPA with multiple DataSources

There is another way to have multiple dataSources by using @EnableAutoConfiguration and application.properties. Basically put multiple dataSource configuration info on application.properties and generate default setup (dataSource and entityManagerFactory) automatically for first dataSource by @EnableAutoConfiguration. But for next dataSource, create dataSource, entityManagerFactory and transactionManager all manually by the info from property file. Below is my example … Read more

setMaxResults for Spring-Data-JPA annotation?

As of Spring Data JPA 1.7.0 (Evans release train). You can use the newly introduced Top and First keywords that allow you to define query methods like this: findTop10ByLastnameOrderByFirstnameAsc(String lastname); Spring Data will automatically limit the results to the number you defined (defaulting to 1 if omitted). Note that the ordering of the results becomes … Read more

What is this spring.jpa.open-in-view=true property in Spring Boot?

The OSIV Anti-Pattern Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram. The OpenSessionInViewFilter … Read more

Spring Boot – Loading Initial Data

You can create a data.sql file in your src/main/resources folder and it will be automatically executed on startup. In this file you can add some insert statements, eg.: INSERT INTO users (username, firstname, lastname) VALUES (‘lala’, ‘lala’, ‘lala’), (‘lolo’, ‘lolo’, ‘lolo’); Similarly, you can create a schema.sql file (or schema-h2.sql) as well to create your … Read more