Java 使用 entityManager.createNativeQuery(query,foo.class)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2110809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
use of entityManager.createNativeQuery(query,foo.class)
提问by Jim Ward
I would like to return a List of Integers from a
我想从一个返回整数列表
javax.persistence.EntityManager.createNativeQuery
call
javax.persistence.EntityManager.createNativeQuery
称呼
Why is the following incorrect?
为什么以下说法不正确?
entityManager.createNativeQuery("Select P.AppID From P", Integer.class);
specifically why do I get "...Unknown entity: java.lang.Integer"
特别是为什么我会得到“...未知实体:java.lang.Integer”
Would I have to create an entity class that has a single field that is an Integer ?
我是否必须创建一个实体类,它具有一个 Integer 字段?
Thanks
谢谢
采纳答案by ewernli
What you do is called a projection. That's when you return only a scalarvalue that belongs to one entity. You can do this with JPA. See scalar value.
您所做的称为投影。那时您只返回属于一个实体的标量值。你可以用 JPA 做到这一点。请参阅标量值。
I think in this case, omitting the entity type altogether is possible:
我认为在这种情况下,完全省略实体类型是可能的:
Query query = em.createNativeQuery( "select id from users where username = ?");
query.setParameter(1, "lt");
BigDecimal val = (BigDecimal) query.getSingleResult();
Example taken from here.
示例取自此处。
回答by Omar Al Kababji
That doesn't work because the second parameter should be a mapped entity and of course Integer is not a persistent class (since it doesn't have the @Entity annotation on it).
这不起作用,因为第二个参数应该是一个映射实体,当然 Integer 不是一个持久类(因为它没有 @Entity 注释)。
for you you should do the following:
对您来说,您应该执行以下操作:
Query q = em.createNativeQuery("select id from users where username = :username");
q.setParameter("username", "lt");
List<BigDecimal> values = q.getResultList();
or if you want to use HQL you can do something like this:
或者,如果您想使用 HQL,您可以执行以下操作:
Query q = em.createQuery("select new Integer(id) from users where username = :username");
q.setParameter("username", "lt");
List<Integer> values = q.getResultList();
Regards.
问候。
回答by Thakhani Tharage
Here is a DB2 Stored Procidure that receive a parameter
这是一个接收参数的 DB2 Stored Procidure
SQL
SQL
CREATE PROCEDURE getStateByName (IN StateName VARCHAR(128))
DYNAMIC RESULT SETS 1
P1: BEGIN
-- Declare cursor
DECLARE State_Cursor CURSOR WITH RETURN for
-- #######################################################################
-- # Replace the SQL statement with your statement.
-- # Note: Be sure to end statements with the terminator character (usually ';')
-- #
-- # The example SQL statement SELECT NAME FROM SYSIBM.SYSTABLES
-- # returns all names from SYSIBM.SYSTABLES.
-- ######################################################################
SELECT * FROM COUNTRY.STATE
WHERE PROVINCE_NAME LIKE UPPER(stateName);
-- Cursor left open for client application
OPEN Province_Cursor;
END P1
Java
爪哇
//Country is a db2 scheme
//Now here is a java Entity bean Method
public List<Province> getStateByName(String stateName) throws Exception {
EntityManager em = this.em;
List<State> states= null;
try {
Query query = em.createNativeQuery("call NGB.getStateByName(?1)", Province.class);
query.setParameter(1, provinceName);
states= (List<Province>) query.getResultList();
} catch (Exception ex) {
throw ex;
}
return states;
}
回答by jmb
JPA was designed to provide an automatic mapping between Objects and a relational database. Since Integer is not a persistant entity, why do you need to use JPA ? A simple JDBC request will work fine.
JPA 旨在提供对象和关系数据库之间的自动映射。既然 Integer 不是持久化实体,那么为什么需要使用 JPA ?一个简单的 JDBC 请求就可以正常工作。
回答by Md. Sajedul Karim
Suppose your query is "select id,name from users where rollNo = 1001".
假设您的查询是“ select id,name from users where rollNo = 1001”。
Here query will return a object with id and name column. Your Response class is like bellow:
这里查询将返回一个带有 id 和 name 列的对象。您的 Response 类如下所示:
public class UserObject{
int id;
String name;
String rollNo;
public UserObject(Object[] columns) {
this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
this.name = (String) columns[1];
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
}
here UserObject
constructor will get a Object Array and set data with object.
这里UserObject
构造函数将获取一个对象数组并使用对象设置数据。
public UserObject(Object[] columns) {
this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
this.name = (String) columns[1];
}
Your query executing function is like bellow :
您的查询执行功能如下所示:
public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {
String queryStr = "select id,name from users where rollNo = ?1";
try {
Query query = entityManager.createNativeQuery(queryStr);
query.setParameter(1, rollNo);
return new UserObject((Object[]) query.getSingleResult());
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
Here you have to import bellow packages:
在这里你必须导入波纹管包:
import javax.persistence.Query;
import javax.persistence.EntityManager;
Now your main class, you have to call this function.
First you have to get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo)
function. Calling procedure is given bellow:
现在你的主类,你必须调用这个函数。首先,您必须获得 EntityManager 并调用此getUserByRoll(EntityManager entityManager,String rollNo)
函数。调用过程如下:
@PersistenceContext
private EntityManager entityManager;
UserObject userObject = getUserByRoll(entityManager,"1001");
Now you have data in this userObject.
现在您在这个 userObject 中有了数据。
Here is Imports
这里是进口
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
Note:
笔记:
query.getSingleResult()return a array. You have to maintain the column position and data type.
query.getSingleResult()返回一个数组。您必须维护列位置和数据类型。
select id,name from users where rollNo = ?1
query return a array and it's [0] --> id and [1] -> name
.
查询返回一个数组,它是[0] --> id and [1] -> name
.
For more info, visit this Answer
有关更多信息,请访问此答案
Thanks :)
谢谢 :)