代码之家  ›  专栏  ›  技术社区  ›  QA_Col

将查询从Postgres传递到JPA

  •  0
  • QA_Col  · 技术社区  · 6 年前

    我是新手

    我正在尝试将此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;
    

    现在,我想编写相同的查询,我有具有相同名称表的实体。

    分类

    @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 回复  |  直到 6 年前
        1
  •  0
  •   Simon Martinelli    6 年前

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

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

    因此,查询如下所示:

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