use of entityManager.createNativeQuery(query,foo.class)

后端 未结 5 657
-上瘾入骨i
-上瘾入骨i 2020-12-01 07:49

I would like to return a List of Integers from a

javax.persistence.EntityManager.createNativeQuery call

Why is the following incorrect?

相关标签:
5条回答
  • 2020-12-01 08:03

    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).

    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:

    Query q = em.createQuery("select new Integer(id) from users where username = :username");
    q.setParameter("username", "lt");
    List<Integer> values = q.getResultList();
    

    Regards.

    0 讨论(0)
  • 2020-12-01 08:10

    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. 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.

    0 讨论(0)
  • 2020-12-01 08:11

    Suppose your query is "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:

    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.

    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:

    @PersistenceContext
    private EntityManager entityManager;
    
    UserObject userObject = getUserByRoll(entityManager,"1001");
    

    Now you have data in this 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.

    select id,name from users where rollNo = ?1 
    

    query return a array and it's [0] --> id and [1] -> name.

    For more info, visit this Answer

    Thanks :)

    0 讨论(0)
  • 2020-12-01 08:15

    Here is a DB2 Stored Procidure that receive a parameter

    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;
    }
    
    0 讨论(0)
  • 2020-12-01 08:17

    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.

    0 讨论(0)
提交回复
热议问题