[英]Inner join using JpaRepository without writing the query
我有某些實體(我通過 Hibernate 鏈接了它們),我想從我的數據庫中查詢它們; 無需顯式寫出查詢。
我的父母.java
@Entity
@Table(name="myparent")
public class MyParent {
@Id
@SequenceGenerator(name = "myparent_id_seq", sequenceName = "myparent_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "myparent_id_seq")
private Long id;
@OneToOne(mappedBy = "myParent", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private MyChild myChild;
public void linkChild(MyChild myChild) {
this.myChild = myChild;
myChild.setParent(this);
}
// rest of code
}
我的孩子
@Entity
@Table(name="myChild")
public class MyChild {
@Id
@SequenceGenerator(name = "mychild_id_seq", sequenceName = "mychild_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "mychild_id_seq")
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "myparent_id")
private MyParent myParent;
// rest of code
}
現在,我想做:
select * from myparent p
inner join mychild c on p.id = c.myparent_id;
-- basically I want to get all instances of MyParent where MyChild is not null
什么會返回一個MyParent
的實例,然后我可以使用我的 getter 和 setter 解析自己。 我在網上找到的所有內容都是明確寫出查詢。
有沒有辦法做到這一點?
您可以使用 jpql:
@Query("select mp from MyParent mp where mp.myChild is not null")
或者您可以使用本機查詢
@Query(value = "select p.* from myparent p inner join mychild c on p.id = c.myparent_id", nativeQuery = true)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.