Announcement Announcement Module
Collapse
No announcement yet.
Spring Data JPA - How to create dynamic JPQL queries Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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
    I'm examining the SimpleJpaRepository implementation, it looks like I can use EntityManager. Is there a simpler way to achieve this?

    Comment


    • #3
      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.

      Comment


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

        Comment

        Working...
        X