我有两个表“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);
}
这将为我提供表 1 中每个 companyId 的行列表以及表 2 中具有相应供应商 ID 的行列表。
到目前为止,我的实现工作正常。
响应是
{
"content": [
{
"vendorId": 23,
"name": "vendorname",
"details": details,
"table2": [
{
"id" :1,
"cityId":1,
},
"id" :2,
"cityId" : 3
]
},
{....}
]
}
目前我正在将companyId作为输入并给出上述响应。现在我也想将 cityId 作为输入。因此 table2 输出应仅包含给定 cityId 的详细信息。
那么有人可以帮助我如何实现它吗?我不想为 table1 和 table2 创建另一个模型。
最佳答案
Page<Table1> findByCompanyIdAndTable2_CityId(Integer companyId, Integer cityId, Pageable pageable);
此方法将负责按 cityId 进行获取。下划线(_) 表示嵌套字段。但要使其发挥作用,您需要急切地获取 Table2。
@OneToMany(mappedBy = "table1",cascade = CascadeType.ALL, fetch=FetchType.EAGER)
关于java - JPA 中的条件 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44047748/