hibernate查询结果映射到实体和map的方法

1.sql查询封装对象,配置映射,把查询出来的数据封装到实体当中:

方法一:addEntity(A.class)设定查询出的结果映射到相应的实体中,但是这个实体必须在hibernate的映射文件中配置了相应的映射

//集合中的Object[], Object[0]即使Person,Object[1]即使MyEvent
public List<Object[]> getMyEvents() {
        String sql = "select p.*,e.* from person_inf as p inner join event_inf as e" +  
                " on p.person_id=e.person_id";  
        List list = session.createSQLQuery(sql)  
               .addEntity("p",Person.class)  
               .addEntity("e", MyEvent.class)  
               .list(); 
        return list;
    } 

方法二:在sql语句中使用构造方法(HQL语句)

Query q = session.createQuery("select new com.hibernate.MsgInfo(m.id, m.cont, m.topic.title, m.topic.category.name) from Msg m");  
List<MsgInfo> list=q.list(); 

2.sql查询封装对象,不用配置映射文件,把查询出来的结果封装到实体中:
方法一:setResultTransformer(Transformers.aliasToBean(PostVO.class));//封装到实体,必须添加addScalar()为每个字段添加类型限制,不然会报错

public List<BusinessConfig> getBusByPid(Long proId, Long busId) throws Exception {
        // TODO Auto-generated method stub
        Session session = this.getSession();
        StringBuffer sql = new StringBuffer();
        sql.append
        ("select distinct business_id as businessId, business_name as businessName, proj_id as pid from view1 where proj_id =");
        sql.append(proId);
        if(busId != null) {
            sql.append(" and business_id=").append(busId);
        }
        Query query = session.createSQLQuery(sql.toString())
                .addScalar("businessId", Hibernate.LONG)
                .addScalar("businessName", Hibernate.STRING)
                .addScalar("pid", Hibernate.LONG)
                .setResultTransformer(Transformers.aliasToBean(BusinessConfig.class));
        return query.list();
    }

方法二:query.setResultSetMapping(”“);
使用一个预定义的ResultSetMapping命名

    SQLQuery query = session.createSQLQuery("...");
    //使用在hbm文件中配置的自定义结果集映射
    query.setResultSetMapping("noteAnduthor");
    query.list();

setResultSetMapping的解释如下(不推荐):

First, in SQL you have to write the name of the table, not the entity name.
Second, your JOIN sentence could be invalid at SQL. There are a few ways to implement a join. I'll take the direct approach (select from both table and stating the join at the where clause).
Suposing that the person entity maps a table called "TABLE_PERSON", and address maps table "TABLE_ADDRESS", a valid query would look as follows:
SELECT person.NAME, person.AGE, person.SEX, 
     address.STREET, address.CITY, address.STATE, address.ZIP 
FROM TABLE_PERSON person, TABLE_ADDRESS address 
WHERE person.ID = address.PERSON_ID
One more point. Checking the hibernate documentation, I have found this example:
List cats = sess.createSQLQuery("select {cat.*}, {kitten.*} from cats cat, cats kitten 
where kitten.mother = cat.id").
     setResultSetMapping("catAndKitten").list();
So, maybe the problem is not at the query itself, but on the resultSet Mapping you are using, and the way to reference the fields.
Let's suppose this mapping (from the Hibernate doc):
<resultset name="personAddress">
    <return alias="person" class="eg.Person"/>
    <return-join alias="address" property="person.mailingAddress"/>
</resultset>
Then, as the exaple states, your query should define the columns between curly brackets ({}), and using the alias you have defined at the mapping:
personList = session.createSQLQuery(
             "SELECT {person.NAME}, {person.AGE}, {person.SEX}, "+
            "{address.STREET}, {address.CITY}, {address.STATE}, {address.ZIP} "+
            "FROM TABLE_PERSON person, TABLE_ADDRESS address "
            "WHERE person.ID = address.PERSON_ID"
        ).setResultSetMapping("personAddress")
         .list();
Please, tell me if any of this examples works.

方法三:封装到map集合中,封装到map集合中,如果添加别名必须添加addScalar()为每个字段添加类型限制,不然会报错,对于oracle中某些类型hibernate没有做对应的映射,例如oracle中的NVARCHAR2类型,仍然需要手动添加映射关系,使用addScalar()方法:

Session session = this.getSession();
        StringBuffer sql = new StringBuffer();
        sql.append
        ("select distinct business_id as businessId, business_name businessName, proj_id pid from view1 where proj_id =");
        sql.append(proId);
        if(busId != null) {
            sql.append(" and business_id=").append(busId);
        }
        Query query = session.createSQLQuery(sql.toString())
                .addScalar("businessId", Hibernate.LONG)
                .addScalar("businessName", Hibernate.STRING)
                .addScalar("pid", Hibernate.LONG)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.list();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值