将查询从Postgres传递给JPA

时间:2018-02-09 17:10:54

标签: java postgresql jpa distinct

我是新手

我正在尝试将此Postgres查询传递给JPA / JPQL

SELECT
    DISTINCT(srv.code) AS Serv_Cod,
    srv.id AS Serv_id,
    srv.description AS Serv_Desc
FROM db.Category AS cat
    join db.Classification AS cla ON cat.id = cla.cat_id
    join db.Service AS srv ON srv.id = cla.srv_id
WHERE cat.id = 10
ORDER BY srv.id;

现在我想编写相同的Query,我的实体具有相同的名称Table。

分类

@Entity
@Table(name = "Classification", schema = "db")
@Audited
public class Classification implements Identifiable<Long> {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "srv_id", nullable = true)
    private Service service;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cat_id", nullable = true)
    private Category category;

    ....

}

服务

@Entity
@Table(name = "Service", schema = "db")
@Audited
public class Service implements Identifiable<Long> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "code", nullable = false)
    private String code;

    @Column(name = "description", nullable = false)
    private String description;

    ....

}

我正在读书,但我很困惑......

我不知道如何为ON编写JOIN,并为列/字段建立DISTINCT。

Long myID = 25L;
this.em.createQuery("SELECT NEW SomeDto(srv.id, srv.code, srv.description)" 
        + " FROM Classification cla"
                    + "JOIN cla·cat_id cat"
                    + "JOIN cla·srv_id srv"
                    + "WHERE cat.id = :id"
        ,BaseObjectDto.class).setParameter("id", myID).getResultList();

感谢您提供宝贵的帮助。

1 个答案:

答案 0 :(得分:0)

查询非常简单。当您拥有ToOne关系时,您可以导航到相关实体。没有必要加入。

即使使用ToMany,也不需要ON,因为这已在映射中定义。

因此查询将如下所示:

SELECT NEW SomeDto(cla.service.id, cla.service.code, cla.service.description)
FROM Classification cla
WHERE category.id = :id