[英]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.