in Spring

Spring JPA Repositories tutorial

Introduction

Using Spring Data JPA repositories can give you head start in the project and save you from boilerplate code. In this post I will show you how to:

  • Wire important beans DataSource, JpaVendorAdapter, EntityManager and TransactionManager
  • Enable JPA repositories using @EnableJpaRepositories
  • Specify Pomodoro entity
  • Create JPA Repository
  • Specify query using method name, @Query annotation with named parameters, using native sql query
  • Specify update query

Wiring data related beans

There are number of data related beans that you need to wire in order to allow your application to access database with transactions enabled. First you need to create data source. Good approach is to have spring Profiles enabled so that you use one datasource for production and other for development like environments. This post can help you with spring profiles.

Datasource

Specifying datasources is done using next lines of code

Here we have two datasource beans created depending of the profile enabled DEV or PRODUCTION. One datasource is BasicDataSource that connects to your database server depending of the environment properties that are set.

For this example I have included app.properties using  @PropertySource. Check more about property place holders here.

JPA vendor adapter

Vendor adapter bean needs to be created here we are using HibernateJpaVendorAdapter with H2 database, show sql , generate Ddl and database plaform h2Dialect.

Note: You might not want to set generateDDl to true since this will add all missing columns and tables in the database.

Entity manager factory

Entity manager factory needs datasource , vendor adapter and packages to scan. Scanned package should have classes annotated with @Entity so that entity manager can pick them up.

Transaction manager

At last we need transactions in our application, for this we will specify transaction manager bean using:

Transaction management needs to be enabled using annotation  @EnableTransactionManagement. There are few parameters you should consider using

  • mode , default is AdviceMode.PROXY. Other option is ASPECTJ.
  • order, default is Ordered.LOWEST_PRECEDENCE
  • proxyTargetClass, default is false

Finally we need to enable JPA repositories using especial annotation

Specified package contains the repositories.

JPA Repositories

Lets create one simple repository that will have CRUD methods

Ok is is really this simple?

Yes , extending CrudRepository interface will create JPA repository that has CRUD methods . If you check the code of CrudRepository

you will notice that it has one annotation @NoRepositoryBean. This annotation tells spring that this class is intermediate repository that is not supposed to be wired.

Beside CrudRepository you have Repository interface, this interface is empty and holds no mehtods. It is up to you if you want to copy method from CrudRepository to allow  for example deleting the entities .

Sorting and paging is done using especial interface

Sort is created using the list of orders that are property with direction ( ascending and discending). Here is a simple example that will sort pomodoros by name.

Pageable allows you to get results in pages and sorted ( sorted is optional ). Here is the Pageable example

PageRequest has few constructors you can use like that can sort results too.

You can decide what spring interface to extend and add your custom methods Repository, CrudRepository or PagingAndSortingRepository. All of them are parameterized using Entity and class of the primary key.

Creating custom queries

Query can be specified in multiple ways, one is of course manually additionally query can be written natively and using method naming.

Lets observe the entity class Pomodoro so that you can understand the custom query part.

Pomodoro entity is simple, it has id and name.

Using method name strategy should be your fist choice since is is easy to use, here is how it goes. One nice example is find pomodoro by name.

List<Pomodoro> findByNameLike(String name);

Method name consists of

  • findBy
  • property name (Name)
  • modifier ( Like)

Lets assume that Pomodoro has some other properties like Description method would be named findByNameLikeAndDescriptionLike.

Spring is packed with modifiers, here is the table picked up from spring reference.

Keyword Sample JPQL snippet
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Between findByStartDateBetween … where x.startDate between 1? and ?2
LessThan findByAgeLessThan … where x.age < ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection<Age> ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection<Age> age) … where x.age not in ?1
True findByActiveTrue() … where x.active = true
False findByActiveFalse() … where x.active = false

If you have complicated query method can be very long and hard to use, then maybe you can use @Query annotation where you can write your query using JPQL.

Annotated method parameters are then mapped to query, here we can map using order of the parameter and using @Param annotation. Here is the example of both

Modifying Query

You can create query that modifies the data, to do this you need to  use annotation @Modifying to tell spring what you want to do. Example

 

Here are few nice examples that will help you write your own queries.

Injecting JPA Repository

To use your custom jpa repository all you need to do is inject it like this

 

In second part i will go through advanced JPA repository features.

Write a Comment

Comment