0

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:

  • All imports are correct (jakarta.persistence.*,)
  • My repository is injected properly
  • The method is being called from the service

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);
1
  • The code looks fine, you might want to enable the property spring.jpa.show-sql=true to verify if the query generated is indeed correct. Commented Apr 23 at 13:01

1 Answer 1

0

@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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the advice, actually the issue was i was not connect to the correct database

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.