Search code examples
javaspring-boothibernatejpa

Cannot query a table with composite key in Hibernate


I have a table with userId and listingId. They together form a composite key.

The key itself:

@Data
@Embeddable
public class FavoriteListingId implements Serializable {
    @Column(name = "user_id", columnDefinition = "CHAR(36)")
    private String userId;

    @Column(name = "listing_id", columnDefinition = "CHAR(11)")
    private String listingId;
}

The table:

@Getter
@Setter
@Entity
@Table(name = "favorite_listing")
public class FavoriteListingEntity {
    @EmbeddedId
    FavoriteListingId id;
}

The repository:

@Repository
public interface FavoriteListingRepository extends JpaRepository<FavoriteListingEntity, FavoriteListingId> {
    int countByListingId(String listingId);

    List<FavoriteListingEntity> findAllByUserId(String userId);
}

But findAllByUserId does not work. It gives me the following error:

No property userId found for type FavoriteListingEntity!

What am I doing wrong here?


Solution

  • Property expressions can refer only to a direct property of the managed entity. However, you can also define constraints by traversing nested properties. See Spring Data JPA documentation.

    To solve the problem, you must specify the name of the parent attribute in which the composite key is located: countByIdListingId and findAllByIdUserId

    @Repository
    public interface FavoriteListingRepository extends JpaRepository<FavoriteListingEntity, FavoriteListingId> {
        
        int countByIdListingId(String listingId);
    
        List<FavoriteListingEntity> findAllByIdUserId(String userId);
    }