sql语句查询,封装到实体

String sql="select * from t_alarm_runningstate where alarm_time = (select alarm_time from t_alarm_runningstate where station_oid = "+stationid+" order by alarm_time desc limit 1) and station_oid = "+stationid+" and alarm_time > '"+beginTime+"'";
List list = new ArrayList();
Query query = super.getSession().createSQLQuery(sql).addEntity(TAlarmRunningstate.class);
list = query.list();
return list;

 

封装部分结果

Query query = session.createSQLQuery("select u.id as {usr.id},u.name as {usr.name},u.age as {usr.age} from t_user u").addEntity("usr",TUser.class); 

 

以前我们讲到,有些团队会规定不给在代码中写SQL语句,这又需要配置文件出马啦。
我们可以在配置文件中添加:

<sql-query name="queryTUser">

 <return alias="usr" entity-name="org.hibernate.tutorial.domain6.TUser" />

 select {usr.*} from t_user usr where name=:name

sql-query>

注意,这里的entity-name需要写完整的包名,不然会报错的。这里我们有子标签return,它指定了表的别名和类名,这样我们在运行时就不需要再addEntity了。
    看代码:

Query query = session.getNamedQuery("queryTUser");

query.setParameter("name","shun");

List list = query.list();

Iterator iter = list.iterator();

 

你可能感兴趣的:(sql语句查询,封装到实体)