Results 1 to 4 of 4

Thread: Spring Data JPA - How to create dynamic JPQL queries

  1. #1
    Join Date
    Dec 2010
    Posts
    315

    Default Spring Data JPA - How to create dynamic JPQL queries

    How do you exactly create dynamic JPQL queries. I have a repository interface and I can call the declared methods. The problem with that is if I have a filtering requirement from the presentation layer I wouldn't know in advance which fields are chosen by the user. With the repository interface it expects we declare already the fields that we'll be using.

    Of course I could probably declare all the possible combination of fields and declare them as methods in the repository and probably have one big if-else statement. But I think that's bad. A JPQL query, like HQL, would be better for this scenario.

    Is this possible? I've checked the docs and all I see are @Query and @NamedQuery but you have to declare it already in the repository interface. Is there a way to pass that query dynamically?

    For example I have the following JPQL query:

    Code:
    select u from User u where u.emailAddress = ?1 and u.lastname = ?2
    How do you pass that query without declaring in the repository?

  2. #2
    Join Date
    Dec 2010
    Posts
    315

    Default

    I'm examining the SimpleJpaRepository implementation, it looks like I can use EntityManager. Is there a simpler way to achieve this?

  3. #3
    Join Date
    Apr 2011
    Posts
    107

    Default

    either you create your own method which create your query and execute it or you can create some Predicate and use them as you need.

  4. #4
    Join Date
    Dec 2010
    Posts
    315

    Default

    Thanks for the lead. I think I'll stick with QueryDSL to lessen the verbosity of JPA 2.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •