Skip to content
Advertisement

Spring Data JPA: FindBy on Join Column

I have setup two entities like below in a one-to-one mapping and I am trying to query on the joincolumn like below in my repository:

@Entity
@Table(name = "a")
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper=false)
public class A extends Auditable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    @Size(min = 1, max = 100)
    private String name;
}


@Entity
@Table(name = "b")
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper=false)
public class B extends Auditable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    @Size(min = 1, max = 100)
    private String name;

    @OneToOne
    @JoinColumn(name="aId", referencedColumnName = "aId")
    private A aId;

}

In my BRepository.java, I am trying to do this:

@Component
public interface BRepository extends JpaRepository<B, Long> {
    List<B> findAllBByA_aId(String aId);
}

I get the following error:

No property a found for type B! Did you mean 'aId'?

Is this not the right way to query on a join column in spring-data??

Advertisement

Answer

Since you have not defined the column name for id in A then the column name will defaults to id. Then in class B, you should change the referencedColumnName to id (or else you can simply skip the referencedColumnName attribute since it can be derived directly from the target entity in an OneToOne relationship)

@Entity
@Table(name = "b")
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper=false)
public class B extends Auditable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    @Size(min = 1, max = 100)
    private String name;

    @OneToOne
    @JoinColumn(name="aId", referencedColumnName = "id")
    private A aId;

}

In repository, you need to annotate it with @Repository annotation to let Spring know it should be treated as a Repository Bean.

@Repository
public interface BRepository extends JpaRepository<B, Long> {
    
    @Query(value="select b from B b where B.aId.id=?1")
    List<B> findAllBByA_aId(String aId);
}

or you can use SPeL directly,

@Repository
public interface BRepository extends JpaRepository<B, Long> {
    
    List<B> findAllByaIdId(String aId);
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement