Hibernate - createNativeQuery with “non-entity class” result

前端 未结 6 1874
清酒与你
清酒与你 2021-01-04 20:13

I\'m new to all this Hibernate/JPA stuff, so i will try to be as clear as possible.

Is there any way in Hibernate to use createNativeQuery to select a single/or mult

相关标签:
6条回答
  • 2021-01-04 20:43

    For Hibernate 5.0

    Query query = getEntityManager().createNativeQuery(sql);
    List<Object[]> objects = query.getResultList();
    System.out.println(objects.get(0)[0]);
    

    https://docs.jboss.org/hibernate/orm/5.0/userguide/html_single/chapters/query/native/Native.html

    0 讨论(0)
  • 2021-01-04 20:45

    In case of Native query or jpql with column name EntityManager Returns a List of array of objects.

    so to get Result List.

    receive it in a

     List<Object[]> listResults = query.getResultList();
    

    then iterate over it:-

    for (Object[] record : listResults) {
    
                //Iterate Logic will come here
    
                        }
    
    0 讨论(0)
  • 2021-01-04 20:45
    String SQL = ".."; //same SQL as you had before
    Query query = getEntityManager().createNativeQuery(SQL); //no entity mapping
    query.setParameter("idContact", 9293L);
    String string = (String)query.getSingleResult();
    System.out.println(string);
    
    0 讨论(0)
  • 2021-01-04 20:49

    Just try to call createNativeQuery() without passing String.class. If the name column is of string-type in database query.getSingleResult() will actually return a String.

    0 讨论(0)
  • 2021-01-04 20:59

    The problem is that you are passing String.class as the second parameter to createNativeQuery. This will make hibernate attempt to use the String.class to create a mapping for the result set. It can only create this mapping from entity classes and String is not an entity class because it isn't mapped to a table.

    Fortunately, the solution is to simply use an overloaded version of createNativeQuery that doesn't require a second parameter.

    String SQL = ".."; //same SQL as you had before
    Query query = getEntityManager().createNativeQuery(SQL); //no entity mapping
    query.setParameter("idContact", 9293L);
    Object string = query.getSingleResult();
    System.out.println(string);
    
    0 讨论(0)
  • 2021-01-04 21:08

    try

    Query query = getEntityManager().createNativeQuery("select name from contact where id_contact = :idContact", String.class);
    query.setParameter("idContact", 9293L);
    List list = query.getResultList();
    if (!list.isEmpty()){ 
        Object string = list.get(0);
        System.out.println(string);
    }
    

    In the Look here

    http://sysout.be/2011/03/09/why-you-should-never-use-getsingleresult-in-jpa

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