在不编写查询的情况下使用 JpaRepository 进行内部连接
Inner join using JpaRepository without writing the query
我有某些实体(我已通过 Hibernate 链接),我想从我的数据库中查询这些实体;无需显式写出查询。
MyParent.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
}
MyChild.java
@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
什么 return 我可以使用我的 getter 和 setter 解析自己的 MyParent
实例。我在网上找到的所有内容都是明确写出查询。
有什么办法吗?
你可以使用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)
你可以这样做:
findByMyChildIsNotNull()
查看 docs,还有更多可能对您有用的关键字。
我有某些实体(我已通过 Hibernate 链接),我想从我的数据库中查询这些实体;无需显式写出查询。
MyParent.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
}
MyChild.java
@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
什么 return 我可以使用我的 getter 和 setter 解析自己的 MyParent
实例。我在网上找到的所有内容都是明确写出查询。
有什么办法吗?
你可以使用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)
你可以这样做:
findByMyChildIsNotNull()
查看 docs,还有更多可能对您有用的关键字。