createNativeQuery选择实体POJO中给出的特定列

时间:2017-05-24 10:09:25

标签: sql oracle hibernate jpa jpql

我有一个名为CUSTOMER的表格,其中包含100多个COLOUMNS。但是我想只选择我在POJO中指定的6列:

实体POJO:

  @Entity
    @Data
    @Table(name = "CUSTOMER")
    public class CustomerEntity {

        @Id
        @Column(name = "C_ID")
        private String customerId;

        @Id
        @Column(name = "C_KEY")
        private String customerKey;

        @Column(name = "NAME")
        private String name;

        @Column(name = "FIRST_NAME")
        private String firstName;

        @Column(name = "LAST_NAME")
        private String lastName;

        @Column(name = "AGE")
        private String age;
    }

NativeQuery:

String query = "select * from CUSTOMER where (C_ID= '1' AND C_KEY= '12') OR (C_ID= '1' AND C_KEY= '13')) AND AGE>25";

Query q = e.createNativeQuery(query,CustomerEntity.class);

[编辑:出于使用原生查询的原因]

选择原生查询的原因:

  1. 我需要在JPA中执行以下复杂查询。
  2. 在复杂查询中,我有子查询,分析方法调用。我假设如果我需要实现这一点,那么本机查询将有所帮助。
  3. 我写的上述本机查询只是为了测试最内层的查询。
  4. 复杂逻辑:

    SELECT * FROM (
     SELECT row_number() over(order by C_ID, C_KEY) RN, FEW-COLUMNS(
        SELECT * FROM BOOK
            WHERE (C_ID, C_KEY) IN (customerId1, customerKey1)
                                   (customerId2, customerKey2)
                                   (customerId3, customerKey3)
                                   .....
    
                                   (customerIdn, customerKeyn) AND ROWNUM <= 340
       )WHERE RN BETWEEN anyNumber and anyNumber 
    )ORDER BY DESC RN;
    

    问题:

    1. 由于它是一个namedQuery,我无法将查询作为

      传递

      String query =“select Customer from CustomerEntity cu where((cu.customerId ='1'AND cu.customerKey = '12')或(cu.customerId ='1'AND cu.customerKey ='13')AND cu.age&gt; 25)“;

    2. 如果我使用此查询,我将获得ORA -00947表或视图不存在异常。

      1. 是否可以只获取特定列?

1 个答案:

答案 0 :(得分:3)

您必须使用别名才能使其正常工作。否则,持久性提供程序将不知道如何执行匹配:

select c_id as customerId, c_key as customerKey...
from CUSTOMER 
where ...

别名应与您映射到的实体类的相应字段名称完全相同。