【问题标题】:createNativeQuery to select specific Columns given in entity POJOcreateNativeQuery 选择实体 POJO 中给定的特定列
【发布时间】:2017-10-24 14:48:19
【问题描述】:

我有一个名为 CUSTOMER 的表,其中包含 100 多个列。但我只想选择我在 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. 上面我写的原生查询只是为了测试最里面的查询。

复杂逻辑:

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. 由于它是一个命名查询,我无法将查询传递为

    String query = "select cu from CustomerEntity cu where ((cu.customerId = '1' AND cu.customerKey = '12') or (cu.customerId = '1' AND cu.customerKey = '13') AND cu.age > 25)";

如果我使用此查询,我会收到 ORA -00947 表或视图不存在异常。

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

【问题讨论】:

  • 您编写的第二个查询看起来不正常。此查询中的“ct”是什么?什么是“cu”?这是您使用的确切查询吗?
  • String query = "select ct from CustomerEntity ct where ((ct.customerId = '1' AND ct.customerKey = '12') or (ct.customerId = '1' AND ct.customerKey = '13') 和 ct.age > 25)";可能是这样
  • @Rjiuk,我的意思是为实体 POJO 保留别名(cu)。现在我编辑了问题。

标签: sql oracle hibernate jpa jpql


【解决方案1】:

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

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

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

【讨论】:

  • 你的意思是我需要为方法createNativeQuery中的每一列使用带有别名的选择查询。 (对于问题表或视图不存在)
  • 是的,您计划在选择中只有 6 列,所以不会很麻烦
  • 好的。但是在我的另一个实体中,我需要选择 40 多列。在那种情况下,如果我选择每个列名,这将是一个大查询?任何简化查询的替代方法
  • 如何在不明确指定的情况下指定列的子集?或者,也许您想选择所有列?那为什么要在这种情况下使用原生查询呢?
  • 本机查询通常总是更快。尽管所有的 orm 好处,包括数据库更改重写,您都只是放松了。尽管由于复杂性,您的查询..我会从中创建一个存储过程并使用 JPA API 来调用过程。如果数据库发生变化,您只需要重写程序而不更改 java 代码/配置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2018-03-28
  • 2016-06-15
  • 2017-05-21
  • 2015-01-06
  • 1970-01-01
相关资源
最近更新 更多