Announcement Announcement Module
Collapse
No announcement yet.
spring data jpa: find single Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • spring data jpa: find single

    hi,

    if i am expecting a single entity to be returned from a find command,
    e.g. findByMyUniqueIndex() is there direct support for that or would
    i create a finder that returned a collection and just work it from there?

    thanks,
    tony.

  • #2
    Tony

    I suggest you read about JPA documentation itself

    BTW perhaps JPA has something like Hibernate uniqueResult

    Person aPerson =
    (Person) session.createQuery("select p from Person p left join fetch p.events where p.id = id").setParameter("pid", personId).uniqueResult();
    it depends about the WHERE clause too

    Comment


    • #3
      Spring Data JPA finders support single entity results for query methods. So simply having an entity type as return type should do the trick. Be aware that you'll get a DataAccessException in case your query returns multiple entities then.

      Cheers,
      Ollie

      Comment


      • #4
        i just saw this, very cool Ollie!

        i have a bad habit of posting, coming up with a work around, and never checking back on my threads.

        i will whip myself like that guy in the da vinci code.

        Comment


        • #5
          Originally posted by Oliver Gierke View Post
          Spring Data JPA finders support single entity results for query methods. So simply having an entity type as return type should do the trick. Be aware that you'll get a DataAccessException in case your query returns multiple entities then.
          Ollie
          I have a finder that, in theory, should only return one result. It's a finder that returns the most recent result for "X", but there is a small risk of two "X" rows containing the same timestamp down to the millsecond, in which case I'm happy with a random selection.

          It would be really conventient if I could set the max results to "1" with an annotation. Without that, I end up with a large amount of boilerplate code. Instead of just a single EntityNameRepository file with an @Query annotition on my finder, I'm ending up with 3 files (EntityNameRepository, EntityNameRepositoryCustom, and EntityNameRepositoryImpl) just to make sure I don't get an exception if there's more than one result.

          I could be wrong, but I would think my problem is a fairly comon use case.

          Comment

          Working...
          X