How to use "findBy" in an Entity with a Composite PK (Hibernate JPA)
38,015
Solution 1
You should include name of embedded key class in repository instead of Long. Try this one (not tested):
public interface ExpirationDAO extends JpaRepository<ExpirationDTO, IdKey> {
public List<ExpirationDTO> findByIdDate(int date);
}
There after findBy
Id
is yours EmbeddedId
and Date
is attribute of embeddable class. And one more thing: if you use only part of embedded key, you can't expect only one result...
Solution 2
You should include name of embedded key class in repository and also add an underscore (_)
Tested below:
public interface ExpirationDAO extends JpaRepository<ExpirationDTO, IdKey> {
public List<ExpirationDTO> findByIdKey_Date(Date date);
}
Author by
Admin
Updated on January 19, 2020Comments
-
Admin over 4 years
I am learning with bootspring.
findByDate(int date);
used to work until I've movedint Date
into the inner class.Now I can save new entries but I can't retrive them byDate
What do I need to change?
@Transactional public interface ExpirationDAO extends JpaRepository<ExpirationDTO, Long> { public ExpirationDTO findByDate(int date); }
and
@Embeddable public static class IdKey implements Serializable{ @NotNull int date; @ManyToOne ProductDTO product; public IdKey(){ } //setters and getters } @EmbeddedId private IdKey id; @NotNull int units; public ExpirationDTO(){ } //setters and getters }
throws this exception:
org.springframework.data.mapping.PropertyReferenceException: No property date found for type ExpirationDTO!