gpt4 book ai didi

mysql - 带连接的 spring data jpa native 查询

转载 作者:行者123 更新时间:2023-11-29 02:15:09 25 4
gpt4 key购买 nike

如何在 spring data jpa 中执行原生查询,同时获取子实体?如果我在子实体对象上有 Eager FetchType,则 spring 数据正在执行 2 个查询。 1 个用于父实体,1 个用于子实体。

有没有办法只执行 1 个 native 查询来获取父实体和子实体?

parent :

@Entity
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@Temporal(TemporalType.TIMESTAMP)
private Date ts;

@ManyToOne(fetch=FetchType.LAZY)
private Child child;
}

child :

@Entity
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@OneToMany(fetch=FetchType.LAZY, mappedBy="parent")
private Parent parent;
}

查询:

public interface ParentRepository extends Repository<Parent, Integer> {
@Query(value = "SELECT * from parents p inner join children c on c.id=p.childId where TIMESTAMPDIFF(SECOND, p.ts, CURRENT_TIMESTAMP) < :interval", nativeQuery = true)
Parent findOneByInterval(@Param("interval") long interval);
}

我正在使用 Hibernate 5、MySQL 以及 Spring Data JPA。

我还尝试将 @NamedEntityGraph 添加到父类,将 @EntityGraph 添加到查询方法,但没有成功。

最佳答案

如果你想要父对象,你可以这样尝试

public interface ParentRepository extends Repository<Parent, Integer> {

@Query(value = "SELECT p.* from parents p inner join children c on c.id=p.childId where TIMESTAMPDIFF(SECOND, p.ts, CURRENT_TIMESTAMP) < :interval", nativeQuery = true)
Parent findOneByInterval(@Param("interval") long interval);
}

(或)Spring data JPA 将为原生 Query 返回对象数组所以,

public interface ParentRepository extends Repository<Parent, Integer> {

@Query(value = "SELECT * from parents p inner join children c on c.id=p.childId where TIMESTAMPDIFF(SECOND, p.ts, CURRENT_TIMESTAMP) < :interval", nativeQuery = true)
List<Object[]> findOneByInterval(@Param("interval") long interval);
}

关于mysql - 带连接的 spring data jpa native 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41007235/

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