简体   繁体   English

使用entityManager.createNativeQuery(query,foo.class)

[英]use of entityManager.createNativeQuery(query,foo.class)

I would like to return a List of Integers from a 我想从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 谢谢

What you do is called a projection . 你做的是一个投影 That's when you return only a scalar value that belongs to one entity. 那是当你只返回一个属于一个实体的量值时。 You can do this with JPA. 您可以使用JPA执行此操作。 See scalar value . 参见标量值

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 . 这里取的例子。

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. 问候。

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 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;
}

Suppose your query is " select id,name from users where rollNo = 1001 ". 假设您的查询是“ select id,来自rollNo = 1001的用户的名称 ”。

Here query will return a object with id and name column. 这里查询将返回一个id和name列的对象。 Your Response class is like bellow: 您的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构造函数将获取一个Object Array并使用object设置数据。

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. 首先,您必须获取EntityManager并调用此getUserByRoll(EntityManager entityManager,String rollNo)函数。 Calling procedure is given bellow: 呼叫程序如下:

@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. query.getSingleResult()返回一个数组。 You have to maintain the column position and data type. 您必须维护列位置和数据类型。

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 :) 谢谢 :)

JPA was designed to provide an automatic mapping between Objects and a relational database. JPA旨在提供对象和关系数据库之间的自动映射。 Since Integer is not a persistant entity, why do you need to use JPA ? 由于Integer不是一个持久的实体,为什么需要使用JPA? A simple JDBC request will work fine. 一个简单的JDBC请求可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM