【问题标题】:spring data jpa find all by example nested collection propertyspring data jpa find all by example嵌套集合属性
【发布时间】:2018-11-07 17:34:41
【问题描述】:

我有两个对象。可以有多个嵌套地址的公司。

@Entity
@Data
@Table(name = "company")
public class Company {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "phone")
    private String phone;

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private List<Address> addresses;
}

地址类如下所示:

@Data
@Entity
@Table(name = "address")
@ToString(exclude = "company")
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Column(name = "postal_code")
    private String postalCode;

    @Column(name = "city")
    private String city;

    @Column(name = "street")
    private String street;

    @JsonIgnore
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "company_id")
    private Company company;
}

如果可能的话,我想以某种方式进行搜索嵌套集合属性的动态查询。我做了一个使用示例匹配器的搜索方法,但结果是错误的。每次我从 DB 那里得到所有东西,不仅是有我正在寻找的地址邮政编码的公司。

我的搜索方法如下:

@PostMapping("/search")
    public List<Company> search(@RequestBody final Company company){
        return companyRepository.findAll(Example.of(company,
                ExampleMatcher.matchingAny()
                        .withIgnoreNullValues()
                        .withIgnorePaths("id")
                        .withStringMatcher(ExampleMatcher.StringMatcher.STARTING)));
    }

在我的数据库中,我有两个对象,这是搜索的结果:

如您所见,我从 DB 收到所有信息,而不是唯一一家地址邮政编码以 1 开头的公司。

【问题讨论】:

    标签: java spring spring-jdbc query-by-example


    【解决方案1】:

    您好,您可以使用Specification&lt;T&gt;

    https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

    为此,您需要从接口 JpaSpecificationExecutor 扩展:

    public interface UserRepository extends JpaRepository<User> ,JpaSpecificationExecutor<User>{
    }
    

    而且你还需要实现你的自定义Specification&lt;T&gt;

    然后你可以使用repository.findAll(你实现的规范);

    春季文档:

    https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaSpecificationExecutor.html

    我认为这很有帮助。

    【讨论】:

    • 谢谢。我想到了这一点,这是解决这个问题的一种选择。另一个选项是查询 DSL。但是我想知道是否可以用qbe解决。
    • 您可以在 List 中创建客户实体填充并创建此类客户实体的示例,然后尝试 findAll() 等。这是有用的链接:kalliphant.com/spring-data-jpa-querybyexample-tutorial
    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-10
    • 1970-01-01
    相关资源
    最近更新 更多