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 if this is possible, and if so how?
Here's my code:
@Entity
@Table(name = "BOOK_UPDATE_QUEUE", indexes = { uniqueConstraints = @UniqueConstraint(columnNames = {
"bookId", "region" }, name = "UK01_BOOK_UPDATE_QUEUE"))
public class QueuedBook implements Serializable {
@Embedded
@NotNull
private BookId bookId;
...
}
@Embeddable
public class BookId implements Serializable {
@NotNull
@Size(min=1, max=40)
private String bookId;
@NotNull
@Enumerated(EnumType.STRING)
private Region region;
...
}
public interface QueuedBookRepo extends JpaRepository<QueuedBook, Long> {
//I'd like to write a method like this, but can't figure out how to search by region,
//when region is actually a part of the embedded BookId
Page<QueuedBook> findByRegion(Region region, Pageable pageable);
}
Can I write a query for this using Spring Data?
This question is related to
java
spring
jpa
spring-data
spring-data-jpa
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;
...
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);
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);
Source: Stackoverflow.com