spring-data-jpaspring-data

Spring Data JPA: How to find one column inside a collection?


I have tried various examples but I could wrap my head around this.

I wanted to access a specific column from a collection. I am trying to get the Status of a Contract from the ProjectContract table.

ProjectContract > ContractStatusCdtb > contractStatCd

Here is my setup:

public class ProjectContract extends Auditable<String> implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "CONT_SEQ_NUM")
    private Integer contractSeqNum;

    @Exclude
    @ManyToOne(cascade = CascadeType.DETACH)
    @JoinColumn(name = "CONT_STAT_CD")
    private ContractStatusCdtb contractStatusCdtb;
    // many fields removed.....
}
@Entity(name="CONTRACT_STATUS_CDTB")
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class ContractStatusCdtb {

    @Id 
    @Column(name = "CONT_STAT_CD")
    private String contractStatCd;

    // some fields removed

}

and this is my repository:

public interface ProjectContractRepository extends JpaRepository<ProjectContract, Integer> {
    public String findContractStatusCdtbContractStatCdByContractSeqNum(Integer contractId);
}

Hibernate is firing query to get the whole ProjectContract. and I am also getting Class Cast error since I am returning String and not ProjectContract.

Can you please give me some pointer where I am doing incorrectly?

Thanks


Solution

  • There are couple of points.

    1. You cannot get individual column. It has to be always an object of type which is mentioned in extends JpaRepository<ProjectContract, Integer> which is ProjectContract in your case.
      So your query is not correct as you can see from the error message. You need to change this to

       public ProjectContract findByContractStatusCdtbContractStatCd(String contractStatCd);
      

    Or uif you expect multiple rows to be returned

    public List<ProjectContract> findByContractStatusCdtbContractStatCd(String contractStatCd);
    
    1. There is another option to retrieve one or more specific columns. For that You need to use Projections. See here