【问题标题】:Conditional where clause in JPAJPA 中的条件 where 子句
【发布时间】:2017-05-18 12:26:29
【问题描述】:

我有两个表“table1”和“table2”。对于 table1 中的每一行,table2 中可以有多个行。为了获取数据,我创建了以下类

@Entity
@EntityListeners(AuditingEntityListener.class) 
@Table(name = "table1", schema = "dbo")
public class Table1 extends BaseDomain{
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Integer vendorId;
  private String name;
  private Integer companyId;
  private String details;

  @OneToMany(mappedBy = "table1",cascade = CascadeType.ALL)
  @NotFound(action = NotFoundAction.IGNORE)
  private Set<Table2> table2;

 // getter and setter for above
}

    @Entity
    @EntityListeners(AuditingEntityListener.class) 
    @Table(name = "table2", schema = "dbo")
    public class Table2 extends BaseDomain{
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Integer id;
      private Integer cityId;
      private Integer companyId;
      @OneToOne
      @JoinColumn(name = "vendorId")
      @JsonIgnore
      private Table1 table1;

     // getter and setter for above
    }

然后我创建了这样的存储库

@Transactional
public interface Table1Repository  extends JpaRepository<Table1, Integer> {

  Page<Table1> findByCompanyId(Integer companyId,Pageable pageable);

}

这将为我提供 table1 中根据 companyId 的行列表以及 Table2 中具有相应 vendorId 的行列表。

到目前为止,我的实现工作正常。

回应是

{
  "content": [
    {
      "vendorId": 23,
      "name": "vendorname",
      "details": details,
      "table2": [
                 {
                  "id" :1,
                 "cityId":1,
                 },
                  "id" :2,
                  "cityId" : 3
                ]
    },
   {....}
]
}

目前我将 companyId 作为输入并给出上述响应。现在我也想将 cityId 作为输入。所以 table2 输出应该只包含给定 cityId 的详细信息。

那么任何人都可以帮助我如何实现它?我不想为 table1 和 table2 创建另一个模型。

【问题讨论】:

  • 在回答之前,在第二个实体上,我认为你应该使用@ManyToOne 而不是@OneToOne
  • 使用 CriteriaBuilder cb 并创建一个 CriteriaQuery query.where 使用 cb.equal 附加所有三个字段。
  • 对不起!我是 JPA 的新手。你能解释一下吗?一些示例代码会有所帮助。

标签: java spring hibernate jpa spring-data-jpa


【解决方案1】:
Page<Table1> findByCompanyIdAndTable2_CityId(Integer companyId, Integer cityId, Pageable pageable);  

此方法将负责按 cityId 获取。 Underscore(_) 指的是嵌套字段。但要使其正常工作,您需要急切地获取 Table2。

@OneToMany(mappedBy = "table1",cascade = CascadeType.ALL, fetch=FetchType.EAGER)

【讨论】:

  • 我还需要按companyId过滤数据
  • 谢谢..让我试试这个
  • 您的数据模型没有 companyId 字段?
  • 否,但表中有一个名为 companyId 的列
  • 你应该在你的数据模型中拥有它,否则 Spring data 无法使用网络名称为你创建查询
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-27
  • 2013-10-11
  • 2015-01-30
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 2011-01-12
相关资源
最近更新 更多