Spring Data JPA with QueryDSL: Repositories made easy

Spring Data JPA removes much boilerplate from repository code and QueryDSL can be used to create clean and reusable query specifications. When combined, we can create powerful repositories with very little code.

Introduction




Repositories are used to retrieve and modify content from a data storage. Most repository implementations consist of boilerplate code that interacts with the desired ORM, for example an EntityManager when using JPA. Spring has created the “Spring Data JPA” project to eliminate this boilerplate repository code.



Spring Data JPA



Spring Data JPA can be used to dramatically minimize, and often even eliminate, a repository implementation. Imagine having the following domain class:




@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String username;
private String firstname;
private String lastname;

...
}


With plain Spring and JPA we would build the following repository implementation:




@Repository
public class JpaUserRepository implements UserRepository {

@PersistenceContext
private EntityManager em;

public Iterable<User> findAll() {
return em.createQuery(
"from User", User.class
).getResultList();
}

public User findByUsername(String username) {
return em.createQuery(
"from User where username = :username", User.class
).setParameter("username", username).getSingleResult();
}

public User save(User user) {
if(user.getId() == null) {
em.persist(user);
} else {
user = em.merge(user);
}
return user;
}
}


Much of the above repository implementation is boilerplate and can be generalized. This is where Spring Data JPA kicks in.




When using Spring Data JPA, we only need to define a repository interface, and the implementation will be provided automatically. So we define the repository interface:




public interface UserRepository
extends CrudRepository<User, Long> {
User findByUsername(String username);
}


And activate the automatic repository implementations in our application context:




<jpa:repositories base-package="com.myproject.repository" />



Now whenever we wire the UserRepository, we will recieve a fully functional repository implementation automatically. The repository will have full CRUD functionality, due to extending the CrudRepository interface, but also custom find behaviour.


Inside the repository interface we defined a findByUsername method, which basically finds a single user with the provided username. These type of findX methods are called “dynamic finder methods”, and will be resolved automatically whenever the naming convention is applied. Spring Data JPA offers quite extensive finder method support, which is more than enough for most repositories. For more information about dynamic finder methods, look at the reference documentation.




So we basically just created a full blown repository bean, having defined only three lines of code. Which is great! But what happens if queries get more complex and the dynamic finder behaviour won’t suffice?



Advanced queries



There are various ways to defining custom queries in Spring Data JPA.

Named queries


One of the easiest techniques is using JPA named queries. We simply define a @NamedQuery on our entity:




@Entity
@NamedQuery(
name = "User.findByTheUsersName",
query = "from User u where u.username = ?"
)
public class User { }


And create a corresponding finder method in our repository interface:




public interface UserRepository {
User findByTheUsersName(String username);
}


So whenever the finder method is invoked, Spring Data JPA will automatically perform our named query and return its results.



@Query


Or we could just directly define a query on our repository interface using annotations:




public interface UserRepository {
@Query("select u from User u where u.firstname = ?")
List<User> findByFirstname(String firstname);
}


Custom implementation


We could even create a custom implementation for some repository method(s). To provide a custom implementation we first define a UserRepositoryCustom interface, with all custom repository methods, and an implementation UserRepositoryImpl. Then we let our UserRepository extend from the custom interface, and Spring Data JPA will automatically wire our custom implementation into the repository bean.

A custom implementation is defined as follows:




public interface UserRepository extends
UserRepositoryCustom, CrudRepository<User, Long> {
// Generated finder method
User findByUsername(String username);
}



public interface UserRepositoryCustom {
// Custom method
List<User> findInactiveUsers();
}



public class UserRepositoryImpl
implements UserRepositoryCustom {

@PersistenceContext
private EntityManager em;

@Override
public List<User> findInactiveUsers() {
return em.createQuery(
"from User where active = false", User.class
).getResultList();
}
}


So we can use Spring Data JPA to create our boilerplate implementations, and yet it is still possible to create custom methods as desired.



Type safe queries



While the above demonstrated techniques for custom queries are powerful, they have one fatal flaw. Our queries are not type safe! Whenever we start refactoring our domain class, e.g. renaming firstname into name, each query involving that property will break. And we will not know about the error until runtime. By making our queries type safe, we are capable of finding faulty queries at compile time, resulting in fewer bugs later on.




With JPA 2.0 it is possible to define type-safe queries using the CriteriaQuery API (See a previous blogpost [in dutch]). Defining a criteria query goes as follows:




LocalDate today = new LocalDate();

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Customer> query = builder.createQuery(Customer.class);
Root<Customer> root = query.from(Customer.class);

Predicate hasBirthday = builder.equal(root.get(Customer_.birthday), today);
Predicate isLongTermCustomer = builder.lessThan(root.get(Customer_.createdAt), today.minusYears(2);
query.where(builder.and(hasBirthday, isLongTermCustomer));
em.createQuery(query.select(root)).getResultList();


Criteria queries allow you to create type safe queries, but they are extremely verbose.



Query DSL


Fortunately there is an open-source project “QueryDSL” that also allows us to specify type-safe queries, but with a much more productive API:




LocalDate today = new LocalDate();

QCustomer customer = QCustomer.customer;
BooleanExpression hasBirthday = customer.birthday.eq(today);
BooleanExpression isLongTermCustomer = customer.createdAt.lt(today.minusYears(2));
new JPAQuery(em)
.from(customer)
.where(hasBirthday.and(isLongTermCustomer))
.list(customer);


When using QueryDSL we require much fewer code, and components. Where JPA required you to have a CriteriaQuery, CriteriaBuilder and Root, we now create our query selection criteria directly from the generated meta model (QCustomer). Also, because the selection criteria (BooleanExpression) is not directly coupled to a query instance, as they are in JPA, we can reuse expressions between different queries.



We could even create a catalog class with all common expressions:




class CustomerExpressions {
public static BooleanExpression hasBirthday() {
LocalDate today = new LocalDate();
return QCustomer.customer.birthday.eq(today);
}
public static BooleanExpression isLongTermCustomer() {
LocalDate today = new LocalDate();
return QCustomer.customer.createdAt.lt(today.minusYears(2));
}
}


And use these expressions directly in our repository implementations!



In the case of boolean expressions we could even combine various common expressions to build more complex domain expressions (specification pattern):




hasBirthday().and(isLongTermCustomer())


QueryDSL + Spring Data JPA



Spring provides full QueryDSL integration with the QueryDslPredicateExecutor interface. Whenever your repository interface extends from this executor interface, it will recieve the following powerful query methods:




T findOne(Predicate predicate);
Iterable<T> findAll(Predicate predicate);
Iterable<T> findAll(Predicate predicate, OrderSpecifier<?>... orders);
Page<T> findAll(Predicate predicate, Pageable pageable);
long count(Predicate predicate);


Allowing us to use our expressions, which extend from Predicate, on the repository:




public void sendGifts() {
Predicate shouldRecieveGiftToday = hasBirthday().and(isLongTermCustomer());
for(Customer customer: customerRepository.findAll(shouldRecieveGiftToday)) {
giftSender.sendGiftTo(customer);
}
}


The above code is readable, and requires no custom repository implementation. However, we made our repository API very wide by allowing any type of customer selection query to be performed. Also QueryDSL has become part of our repository API, meaning it is no longer encapsulated strictly in our repository implementation.



It is often more desirable to provide a strict repository API, that in our case would only offer a findAllLongtermCustomersWithBirthday() method. But then you would be forced to create a custom implementation. Fortunately a support class is provided:




public class CustomerRepositoryImpl
extends QueryDslRepositorySupport
implements CustomerRepositoryCustom {

public Iterable<Customer> findAllLongtermCustomersWithBirthday() {
QCustomer customer = QCustomer.customer;
return from(customer)
.where(hasBirthday().and(isLongTermCustomer()))
.list(customer);
}

}


Spring Data JPA looks to drastically improve repository construction. Personally I cannot wait for it to be released!



For more information about Spring Data JPA read:


72 comments:

  1. Henno Vermeulen8/5/13 18:52

    That is a collection of some pretty powerful things! Instead of Spring Data we implemented a "generic DAO" pattern where a DAO/repository for any type can be created by extending the generic DAO interface and extending the implementation. However I'm still using plain JPQL and I was planning on adopting the Criteria API to prevent code duplication between my queries. I was also planning to use helper methods to create the common expressions similar to your "CustomerExpressions" class, but the implementations of these methods seems to be more concise and have less dependencies so are more easily reused. Also I find the syntax for QueryDSL easier so I guess I should give it a try!

    ReplyDelete
  2. And what about implementation of custom methods in the Spring Data Repository?
    I mean some methods which contains a little more complex logic then findOne, delete, update etc.
    It will be greate to highlight this question in this post

    ReplyDelete
  3. chillworld19/7/13 20:07

    @java spring dev:
    use the annotation @query and write the sql query what you want with the complexity you want.
    otherwise you can implement through keywords like :

    List findPersonsByFirstNameContaingOrLastNameContaining(String firstName, String lastName);

    put this in interface and you get a list of all persons who has the piece of firstname or the piece of lastname in them.

    greetz chill.

    ReplyDelete
  4. Great article... But how does these Q classes get generated? When i extend QueryDslPredicateExecutor for a single repository(a single entity), I see that the Q classes are generated for all the entities within my project. Is there a way to limit Q class generation only to the extended repository or to a required entity?

    ReplyDelete
  5. Elon Musk concurs with Hawking however it brisk to call attention to that evident man-made reasoning is still a significant ways away. ai courses

    ReplyDelete
  6. Saved as a favorite, I like your site! onsite mobile repair bangalore Excellent post. I'm dealing with a few of these issues as well.. asus display repair bangalore Way cool! Some extremely valid points! I appreciate you writing this write-up and the rest of the site is very good. huawei display repair bangalore

    ReplyDelete
  7. Excellent blog you have here.. It’s hard to find excellent writing like yours these days. I seriously appreciate individuals like you! Take care!! online laptop repair center bangalore This is a topic that's near to my heart... Thank you! Exactly where are your contact details though? dell repair center bangalore

    ReplyDelete
  8. Everything is very open with a precise description of the challenges. It was truly informative. Your site is extremely helpful. Many thanks for sharing! macbook repair center bangalore I must thank you for the efforts you have put in penning this website. I'm hoping to check out the same high-grade content from you in the future as well. In fact, your creative writing abilities has motivated me to get my own, personal site now ;) acer repair center bangalore

    ReplyDelete
  9. Hello, this weekend is good for me, since this time i am reading this enormous informative article here at my home. website laten maken weert

    ReplyDelete
  10. i never know the use of adobe shadow until i saw this post. thank you for this! this is very helpful. seo heerlen

    ReplyDelete
  11. This is my first time visit to your blog and I am very interested in the articles that you serve. Provide enough knowledge for me. Thank you for sharing useful and don't forget, keep sharing useful info: SEO amersfoort

    ReplyDelete
  12. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. woning kopen venlo

    ReplyDelete
  13. This is my first time visit to your blog and I am very interested in the articles that you serve. Provide enough knowledge for me. Thank you for sharing useful and don't forget, keep sharing useful info: website laten maken maastricht

    ReplyDelete
  14. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work Zonnepanelen zuid limburg

    ReplyDelete
  15. Ik ga dit lezen. Ik zal zeker terugkomen. bedankt voor het delen. en ook Dit artikel geeft het licht waarin we de realiteit kunnen observeren. dit is erg mooi en geeft diepgaande informatie. bedankt voor dit leuke artikel ...
    iphone 11 hoesje

    ReplyDelete
  16. Awesome article, it was exceptionally helpful! I simply began in this and I'm becoming more acquainted with it better! Cheers, keep doing awesome! rijschool eindhoven

    ReplyDelete
  17. When your website or blog goes live for the first time, it is exciting. That is until you realize no one but you and your. 7 persoons auto huren

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work. bakwagen met laadklep

    ReplyDelete
  20. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work. bakwagen met laadklep

    ReplyDelete
  21. This comment has been removed by the author.

    ReplyDelete
  22. Very efficiently written information. It will be beneficial to anybody who utilizes it, including me. Keep up the good work. For sure i will check out more posts. This site seems to get a good amount of visitors. telefoonhoesje

    ReplyDelete
  23. Ik vind je bericht leuk. Het is goed om je vanuit je hart te zien spreken en duidelijkheid over dit belangrijke onderwerp kan gemakkelijk worden waargenomen …
    slotenspecialist heerlen

    ReplyDelete
  24. Ik ben onder de indruk. Ik denk niet dat ik iemand heb ontmoet die zoveel over dit onderwerp weet als jij. Je bent echt goed geïnformeerd en zeer intelligent. Je schreef iets dat mensen konden begrijpen en maakte het onderwerp voor iedereen intrigerend. Echt een geweldige blog die je hier hebt.
    boksautomaat huren

    ReplyDelete
  25. Ik wilde je bedanken voor deze uitstekende lees !! Ik hield absoluut van elk klein beetje ervan. Ik heb je een bladwijzer van je site gemaakt om de nieuwe dingen te bekijken die je plaatst.
    driving lessons den haag

    ReplyDelete
  26. This particular is usually apparently essential and moreover outstanding truth along with for sure fair-minded and moreover admittedly useful My business is looking to find in advance designed for this specific useful stuffs… juridische advies

    ReplyDelete
  27. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work. driving lessons Eindhoven

    ReplyDelete
  28. Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks architect roermond

    ReplyDelete
  29. You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. bedrijfsrapportage

    ReplyDelete
  30. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. architect arnhem

    ReplyDelete
  31. When your website or blog goes live for the first time, it is exciting. That is until you realize no one but you and your. verhuisbus huren maastricht

    ReplyDelete
  32. Really I enjoy your site with effective and useful information. It is included very nice post with a lot of our resources.thanks for share. i enjoy this post. kasteel kopen

    ReplyDelete
  33. Bedankt voor een zeer interessante blog. Wat kan ik anders dat soort informatie in zo'n perfecte aanpak krijgen? Ik heb een onderneming waar ik nu gewoon mee bezig ben en ben op zoek geweest naar dergelijke info.
    monumenten subsidie

    ReplyDelete
  34. Hallo, dit weekend is goed voor mij, want deze keer lees ik dit enorme informatieve artikel hier bij mij thuis.

    taxatie heuvelland

    ReplyDelete
  35. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. makelaar zuid limburg

    ReplyDelete
  36. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. exclusief buitenverblijf

    ReplyDelete
  37. I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. auto huren stein

    ReplyDelete
  38. Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. auto huren echt

    ReplyDelete
  39. Awesome article, it was exceptionally helpful! I simply began in this and I'm becoming more acquainted with it better! Cheers, keep doing awesome! rijschool maastricht

    ReplyDelete
  40. Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work. houten poolhouse limburg

    ReplyDelete
  41. Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. houten veranda op maat

    ReplyDelete
  42. i never know the use of adobe shadow until i saw this post. thank you for this! this is very helpful. rijschool vrachtwagen maastricht

    ReplyDelete
  43. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work gevorderden excel cursus

    ReplyDelete
  44. Ik ga dit lezen. Ik zal zeker terugkomen. bedankt voor het delen. en ook Dit artikel geeft het licht waarin we de realiteit kunnen observeren. dit is erg mooi en geeft diepgaande informatie. bedankt voor dit leuke artikel ...
    excel cursus online

    ReplyDelete
  45. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work. glazenwasser helmond

    ReplyDelete
  46. When your website or blog goes live for the first time, it is exciting. That is until you realize no one but you and your. makelaardij roermond

    ReplyDelete
  47. Hello, this weekend is good for me, since this time i am reading this enormous informative article here at my home. bronboring

    ReplyDelete
  48. Yes i am totally agreed with this article and i just want say that this article is very nice and very informative article.I will make sure to be reading your blog more. You made a good point but I can't help but wonder, what about the other side? !!!!!!Thanks autorijschool voerendaal

    ReplyDelete
  49. I am impressed. I don't think Ive met anyone who knows as much about this subject as you do. You are truly well informed and very intelligent. You wrote something that people could understand and made the subject intriguing for everyone. Really, great blog you have got here. e sigaret

    ReplyDelete
  50. I was surfing the Internet for information and came across your blog. I am impressed by the information you have on this blog. It shows how well you understand this subject. slotenspecialist sittard

    ReplyDelete
  51. You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this... goedkope veranda

    ReplyDelete
  52. Bedankt omdat u bereid bent geweest om informatie met ons te delen. we zullen altijd alles waarderen wat je hier hebt gedaan omdat ik weet dat je je erg druk maakt om onze.
    e sigaret kopen

    ReplyDelete
  53. i never know the use of adobe shadow until i saw this post. thank you for this! this is very helpful. glazen schuifdeuren veranda

    ReplyDelete
  54. We zijn erg dankbaar voor je blogpost. Je zult veel benaderingen vinden na het bezoeken van je bericht. Ik was precies op zoek naar. Bedankt voor dit bericht en ga zo door. Goed gedaan.slotenspecialist geleen

    ReplyDelete
  55. Awesome article, it was exceptionally helpful! I simply began in this and I'm becoming more acquainted with it better! Cheers, keep doing awesome! yoga limburg

    ReplyDelete
  56. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. datzitt terrasstoelen

    ReplyDelete
  57. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. buteyko cursus

    ReplyDelete
  58. Really I enjoy your site with effective and useful information. It is included very nice post with a lot of our resources.thanks for share. i enjoy this post. sexy lingerie

    ReplyDelete
  59. Really I enjoy your site with effective and useful information. It is included very nice post with a lot of our resources.thanks for share. i enjoy this post. rijschool sittard

    ReplyDelete
  60. Hello, this weekend is good for me, since this time i am reading this enormous informative article here at my home. rijschool geleen

    ReplyDelete
  61. You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. huis kopen maastricht

    ReplyDelete
  62. Awesome article, it was exceptionally helpful! I simply began in this and I'm becoming more acquainted with it better! Cheers, keep doing awesome! makelaar meerssen

    ReplyDelete
  63. Such an interesting article here.I was searching for something like that for quite a long time and at last I have found it here. Sex Education Jacket

    ReplyDelete

  64. very nice article , i found something more intresting
    Green Lantern Logo Jacket

    ReplyDelete
  65. I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. Thanks for sharing the information keep updating, looking forward to more posts. High Quality Product Images

    ReplyDelete
  66. Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely helpful for me. buy real likes for instagram uk

    ReplyDelete
  67. thanks for the tips and information..i really appreciate it.. Data Blending in Tableau

    ReplyDelete
  68. Dedicated slide scanners are generally more capable than photo slide scanners, although they are improving PYLE 22MP SLIDE FILM SCANNER

    ReplyDelete