简体   繁体   中英

Select non-entities with JPA?

Is it possible with JPA to retrieve a instances of a non-entity classes with native queries?
I have a non-entity class that wraps two entities:

class Wrap{
  Entity1 ent1;
  Entity2 ent2
}
@Entity
class Entity1{
  ...
}
@Entity
class Entity2{
  ...
}

How can I do something like that?

Query q = entityManager.createNativeQuery("native select here");
List<Wrap> list = q.getResultList();

Is it possible with JPA to retrieve a instances of a non-entity classes with native queries?

No. Native queries can return entities only (if you tell them to do so by passing the resultClass or a resultSetMapping to the createNativeQuery method; if you don't, you will get collections of raw data).

In JPQL, you can use constructor expressions (SELECT NEW...) whith a non-entity constructor. But this is not supported for native queries, you'll have to do it manually.

JPA native query without entity - especially with complex queries (recursive, multiple joins, etc.)?

This worked for me, but it's hibernate specific:

import org.hibernate.transform.Transformers;

Query query = entityManagerFactory.createEntityManager().createNativeQuery(SQL);
// Transform the results to MAP <Key, Value>
query.unwrap(org.hibernate.SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
query.setParameter("myNamedParam", myParam);
List<Map<String, Object>> list = query.getResultList();
for (Map<String, Object> map : list) {
    System.out.println(map);
}

cf. https://www.programmerall.com/article/89371766511/

I think I found the solution. There is a way to use the NEW keyword in constructing the query. What I did to resovle this issue :

    public List<ProductType> getProductByName(String productName) {
        String sqlQuery = "select DISTINCT **NEW** project1.ProductType(o.name, o.revision) from Lhproduct o where o.name = :prodname";
        Query qry = getEntityManager().**createQuery(sqlQuery);**
        qry.setParameter("prodname",productName);
        return qry.getResultList();
 }

The ProductType is a non-entity object, a simple plain object implementing Serialiabale. But you need to define the appropriate constructor.

Happy coding :-)

Thanks and Regards, Hari

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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