简体   繁体   English

Spring Data JPA:连接列上的 FindBy

[英]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:我已经在一对一映射中设置了两个如下所示的实体,并且我正在尝试在我的存储库中查询如下所示的 joincolumn:

@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:在我的BRepository.java ,我试图这样做:

@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??这不是查询 spring-data 中连接列的正确方法吗?

Since you have not defined the column name for id in A then the column name will defaults to id .由于您尚未在 A 中为id定义列名,因此列名将默认为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)然后在 B 类中,您应该将referencedColumnName更改为id (否则您可以简单地跳过referencedColumnName属性,因为它可以直接从 OneToOne 关系中的目标实体派生)

@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批注对其进行注释,以让 Spring 知道它应该被视为存储库 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,或者你可以直接使用 SPeL,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM