无法将本机sql查询转换为jpa查询

时间:2018-02-17 20:37:28

标签: spring postgresql spring-data-jpa

您好我是jpql的新手,并使用postgres的spring数据jpa,我无法翻译下面的查询。

    select 
    "user".table_1.id, "user".table_2.name,
    "user".table_2.email
    from 
    "user".table_1 
    left outer join 
    "user".table_2
    on 
    "user".table_1.table2_id = "user".table_2.id
    where 
    "user".table_1.parent_id=5

以下是我的模型类

@entity
@table(name="table_1)
class Table1{

@id
@GeneratedValue
private Long id;

@OneToOne(mappedBy = "table_2")
private Table2 table_2;

@ManyToOne
@JoinColumn(name = "parent_id")
private Table1 parent_id;

@OneToMany(mappedBy = "account", fetch = FetchType.LAZY)
private List<Table1> childs;
}

@entity
@table(name="table_2)
class Table2
{
@id
private Long id;
private String emailId;
private String name;

@OneToOne
@JoinColumn(name = "table1_id")
private Table1 table1;

}

由于我正在使用带有弹簧数据的DTO而且我需要帮助,所以我无法解决这个问题。

这是我最好的尝试:

 @query("select t1.id, t2.name,t2.email from Table1 t1 left outer join
 t2.table_2 where t1.parent_id=?1") 
public List<CustomDTO>findByParentId(Long parentId);

public class CustomDTO{
private Long table1Id;
private String name;
private String email;
}

我无法解决此错误,因为我将hibernate qwery作为

select
       table10_.id as col_0_0_,
       table21_.name as col_1_0_,
       table21_.email as col_2_0_
           from
       "user".table1 table0_     
           left outer join
       "user".table2 table_21_ 
           on table10_.id=table_21_.table_1     where
       table0_.parent_id=?

请帮我解决这个错误 如果您需要任何帮助,请告诉我们。 谢谢:))

1 个答案:

答案 0 :(得分:1)

您的JPA查询看起来像(未经过测试)

@Query("select t1.id as table1Id, t2.name as name ,t2.emailId as email from Table1 t1 join table_2 t2 where t1.parent_id= :parentId") 
public List<CustomDTO>findByParentId(Long parentId){

public interface CustomDTO{
  private Long table1Id;
  private String name;
  private String email;

}