gpt4 book ai didi

java - 使用 JpaRepository 进行内连接,无需编写查询

转载 作者:行者123 更新时间:2023-12-01 17:41:35 24 4
gpt4 key购买 nike

我有某些实体(我已通过 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

什么会返回一个 MyParent 的实例,然后我可以使用我的 getter 和 setter 来解析它。我在网上找到的所有内容都是明确写出查询。

有什么办法可以做到这一点吗?

最佳答案

您可以使用jpql:

@Query("select mp from MyParent mp where mp.myChild is not null")

或者您可以使用 native 查询

@Query(value = "select p.* from myparent p inner join mychild c on p.id = c.myparent_id", nativeQuery = true)

关于java - 使用 JpaRepository 进行内连接,无需编写查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60421155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com