简体   繁体   中英

How to map query to non-entity class + entity class

I know how to do query to resultClass mapping in IBatis.

How can I map the native query result to the object that is a mix of entity class and scalars in hibernate ? How can I set the parameters ?

Please Help.

With Hibernate Session API, you can do it by comining addEntity() and addScalar() methods:

Query q = s.createSQLQuery(
    "select p.*, count(e.id) as c " +
    "from Project p left join Employee e on p.id = e.project_id " +
    "group by p.id")
    .addEntity(Project.class).addScalar("c");

In JPA you can do it with @SqlResultSetMapping :

@SqlResultSetMappings(
    @SqlResultSetMapping(name = "projectWithCount"
        entities = @EntityResult(entityClass = Project.class),
        columns = @ColumnResult(name = "c")))

...

Query q = s.createSQLQuery(
        "...", "projectWithCount")

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