首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Spring JPA -获取所有子元素

Spring JPA -获取所有子元素
EN

Stack Overflow用户
提问于 2018-07-17 05:33:08
回答 3查看 3.1K关注 0票数 0

我有以下POJO

过滤器->过滤组件

代码语言:javascript
复制
@Entity
public class Filter {

            @Id
            @GeneratedValue(strategy = GenerationType.AUTO)
            private int id;
            private String name;
    //Setters and getters are not shown 

我有下面的子类

代码语言:javascript
复制
@Entity    
public class FilterComponents {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private int id;
        private int component_id;
        private int component_type;

        @ManyToOne
        @JoinColumn(name = "filter_id")
        private Filter filter;
//Setters and getters are not shown

我创建了一个存储库来查询过滤器

代码语言:javascript
复制
public interface FilterRepository extends JpaRepository <Filter, Long> {}

我调用findAll()函数来获取所有的过滤器。该函数工作正常;但是,它只返回每个过滤器的名称和id。

有没有办法也返回相应的过滤器组件?我假设我可以编写一个连接查询,但我有一种感觉,有一种更简洁的方法!

谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-07-17 09:06:13

Make Filter to FilterComponents a OneToMany单向映射。因此,您将在其父FilterComponents内管理子its。

代码语言:javascript
复制
@Entity
public class Filter {
            @Id
            @GeneratedValue(strategy = GenerationType.AUTO)
            private int id;
            private String name;
            @OneToMany
            @JoinColumn(name = "filter_id")
            private List<FilterComponents> filterComponenets;
}

@Entity    
public class FilterComponents {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private int id;
        private int component_id;
        private int component_type;

        // Removed mapping 
}
票数 0
EN

Stack Overflow用户

发布于 2018-07-17 06:15:40

您可能遗漏的是FilterfilterComponents字段,例如

代码语言:javascript
复制
public class Filter {
  ...

  @OneToMany(mappedBy="cart")
  private List< FilterComponents> filterComponents;

您可以在此处根据您的需要定义急切或延迟抓取

票数 0
EN

Stack Overflow用户

发布于 2018-07-17 06:20:41

您的Filter实体与FilterComponent实体没有任何显式关联。在这种情况下,您需要执行另一个请求,以选择具有给定筛选器id的所有筛选器组件。

另一方面,您可以在Filter实体中声明以下字段:

代码语言:javascript
复制
@OneToMany(mappedBy = "filter", fetch = FetchType.EAGER)
private List<FilterComponent> filterComponents;

并且总是迫不及待地加载过滤器组件。

如果急切加载不适合您,您可以使用带有left join fetch的自定义查询

代码语言:javascript
复制
select distinct f from Filter f left join fetch f.filterComponents c
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51370383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档