spring join jpa原生查询与join

时间:2016-12-07 00:11:44

标签: mysql hibernate jpa spring-data spring-data-jpa

如何在spring数据jpa中执行本机查询,同时获取子实体?如果我在子实体对象上有Eager FetchType,则spring数据正在执行2个查询。 1代表父代,1代表子代理。

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

父:

@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;
}

子:

@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添加到Parent类,将@EntityGraph添加到查询方法中,但没有运气。

2 个答案:

答案 0 :(得分:1)

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

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);
}

(OR) Spring数据jpa将返回本机Querys的对象数组 所以,

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);
}

答案 1 :(得分:0)

对我有用的解决方案如下

 @Query(value = "select distinct f.* " + 
        "from form as f " + 
        "inner join form_action as fa on f.id= fa.form_id " + 
        "where  rfa.rol_id = :rol_id", nativeQuery = true)
List<Form> findFormByRolIdParamsNative(@Param("rol_id") Long rol_id);