【发布时间】: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