java - 如何在jpa中以一对多关系选择孩子
问题描述
我想选择我想要的有孩子的父母。
但是当我选择我的父母时,我必须向所有孩子展示
我怎样才能做到这一点?
例子:
public class parent{
private Integer id;
@OnetoMany
@JoinColumn(name="parentId")
private List<child> children;
}
public class child{
private Integer id;
private Integer parentId;
}
findByIdAndchildType(Integer id, String type)
我想看看:父母(id)-> 孩子(类型)
但我可以看到 parent(id) -> child(othertype), child(othertype1), child(type)
解决方案
在我看来,您正在尝试建立双向关系。这可以通过将映射添加到关系的两侧来实现。
例如,将@ManyToOne
映射添加到Child
实体。请注意,您可能应该删除您的parentId
字段,因为现在您可以使用child.getParent().getId()
.
@Entity
public class Child {
@Id
private Integer id;
@ManyToOne
@JoinColumn(name = "parentId")
private Parent parent;
// Remove parentId field
// Getters + Setters ...
}
注意:如果要保留该
parentId
字段,则必须选择要用于插入和更新实体的两个映射 (getParentId()
或)。getParent().getId()
另一个字段应该同时具有insertable = false
和updatable = false
。
下一步是更改@OneToMany
要使用的映射mappedBy
:
@Entity
public class Parent {
@Id
private Integer id;
@OneToMany(mappedBy = "parent") // Change this
private List<Child> children;
// Getters + Setters ...
}
如果要检索特定子项及其父项,您现在可以为Child
实体创建一个存储库:
public interface ChildRepository extends JpaRepository<Child, Integer> {
}
之后,您可以使用以下方法获取特定的孩子:
Optional<Child> child = repository.findById(123); // 123 is the ID of the child in this case
Optional<Parent> parent = child.map(Child::getParent);
使用 Spring boot 1.x 将是:
Child child = repository.findOne(123);
Parent parent = null;
if (child != null) {
parent = child.getParent();
}
推荐阅读
- python - 如何解决在本地运行我的 python 代码?
- laravel - Laravel 使用 id session regenerate 登录
- scala - IN 聚合,基于 SUM,使用 Scala 在 Apache Spark Dataframe 中选择特定的行值
- android - TabLayout内RecyclerView的滚动问题
- c++ - qsort 的比较函子的分段错误
- elasticsearch - Elasticsearch如何在查询时检索文件字段
- r - 可以从 R 中的 lapply 函数返回命名列表吗?
- r - 如何从R中的列中的每个值中减去数据框中特定位置的数字
- c# - Nunit如何使用可并行化的顺序?
- php - CAKEPHP- 每个页面上基于数据库的导航