Spring Data JPA find by embedded object property

前端 未结 4 1023
小蘑菇
小蘑菇 2020-12-02 09:29

I want to write a Spring Data JPA repository interface method signature that will let me find entities with a property of an embedded object in that entity. Does anyone know

相关标签:
4条回答
  • 2020-12-02 09:56

    If you are using BookId as an combined primary key, then remember to change your interface from:

    public interface QueuedBookRepo extends JpaRepository<QueuedBook, Long> {
    

    to:

    public interface QueuedBookRepo extends JpaRepository<QueuedBook, BookId> {
    

    And change the annotation @Embedded to @EmbeddedId, in your QueuedBook class like this:

    public class QueuedBook implements Serializable {
    
    @EmbeddedId
    @NotNull
    private BookId bookId;
    
    ...
    
    0 讨论(0)
  • 2020-12-02 10:04

    This method name should do the trick:

    Page<QueuedBook> findByBookIdRegion(Region region, Pageable pageable);
    

    More info on that in the section about query derivation of the reference docs.

    0 讨论(0)
  • 2020-12-02 10:08

    The above - findByBookIdRegion() did not work for me. The following works with the latest release of String Data JPA:

    Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);
    
    0 讨论(0)
  • 2020-12-02 10:22

    According to me, Spring doesn't handle all the cases with ease. In your case the following should do the trick

    Page<QueuedBook> findByBookIdRegion(Region region, Pageable pageable);  
    

    or

    Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);
    

    However, it also depends on the naming convention of fields that you have in your @Embeddable class,

    e.g. the following field might not work in any of the styles that mentioned above

    private String cRcdDel;
    

    I tried with both the cases (as follows) and it didn't work (it seems like Spring doesn't handle this type of naming conventions(i.e. to many Caps , especially in the beginning - 2nd letter (not sure about if this is the only case though)

    Page<QueuedBook> findByBookIdCRcdDel(String cRcdDel, Pageable pageable); 
    

    or

    Page<QueuedBook> findByBookIdCRcdDel(String cRcdDel, Pageable pageable);
    

    When I renamed column to

    private String rcdDel;
    

    my following solutions work fine without any issue:

    Page<QueuedBook> findByBookIdRcdDel(String rcdDel, Pageable pageable); 
    

    OR

    Page<QueuedBook> findByBookIdRcdDel(String rcdDel, Pageable pageable);
    
    0 讨论(0)
提交回复
热议问题