【发布时间】: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);
[编辑:使用原生查询的原因]
选择原生查询的原因:
- 我需要在 JPA 中执行以下复杂查询。
- 在复杂查询中,我有子查询,解析方法调用。我假设如果我需要实现这一点,那么本机查询会有所帮助。
- 上面我写的原生查询只是为了测试最里面的查询。
复杂逻辑:
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;
问题:
-
由于它是一个命名查询,我无法将查询传递为
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 表或视图不存在异常。
- 是否可以只获取特定的列?
【问题讨论】:
-
您编写的第二个查询看起来不正常。此查询中的“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