I'm working on a Spring Boot project using JPA and trying to query an entity that uses a composite primary key with @IdClass, but I can't get the repository method to work.
I've double-checked that:
Is my setup correct? Should I be watching out for something specific when using @IdClass
with Spring Data JPA?
Entity:
@Entity
@Table(name = "entity_relation", schema = "my_schema")
@IdClass(EntityRelationKey.class)
public class EntityRelation {
@Id
private Long groupId;
@Id
private Integer sequenceNo;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "entity_id", referencedColumnName = "id")
private MainEntity mainEntity;
}
Composite Key Class:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class EntityRelationKey implements Serializable
{ private Long groupId;
private Integer sequenceNo;
}
Repository:
@Repository
public interface EntityRelationRepository extends JpaRepository<EntityRelation, EntityRelationKey> {
List<EntityRelation> findByGroupIdOrderBySequenceNoAsc(@Param("groupId") Long groupId);
}
PROBLEM
When I call this method from my service, it returns empty:
List<EntityRelation> relations = entityRelationRepository.findByGroupIdOrderBySequenceNoAsc(groupId);
@Param
annotation is usually used with Query
annotation to solve binding parameter errors, but since you already used JPA query method, JPA will try to match and bind the parameter you provided with the where condition so you don't need to put @Param
in the method declarations.
you can either try these two things
first try removing @Param
annotation in your repository query method definition
or second try manually creating the query with @Query
annotation
for more detailed and example here is the reference link