使用原生SQL查询必须注意:程序必须选出所有的数据列才可被转换成持久化实体。
假设实体在映射时有一个<many-to-one../>的关联指向另外一个实体,则SQL查询中必须返回该<many-to-one../>映射的外键列,否则将导致抛出"column not found"异常。最简单的做法是,在SQL字符串中使用星(*)来表示返回所有列。
在原生SQL语句中一样支持使用参数,这些参数即可使用问号参数(?),也可使用名字参数。
实战技巧:优化使用名字参数的形式,因为问号参数已经过时
示例1:名字参数
public void entityQuery(){
Seesion session=HibernateUtil.currentSession();
Transaction tx=session.beginTransaction();
String sqlString="Select * From strudent Where year =:year";
List l=session.createSQLQuery(sqlString)
.addEntity(Strudent.class)
.setParameter("year",2015)
.list();
tx.commit();
HibernateUtil.closeSession();
}
示例2:问号(?)参数
public void listInstalledOrUn() {
try {
StringBuilder mysql = new StringBuilder();
mysql.append("SELECT t.*,c.*,p.* FROM (SELECT * FROM vrv_paw_reportlog WHERE TYPE IN(1001,1002) GROUP BY pcInfoId ORDER BY TIME DESC) "
+"t INNER JOIN vrv_paw_cloudaccount c ON t.cloudAccountId=c.id INNER JOIN vrv_paw_pcinfo p ON t.pcInfoId=p.id WHERE 1=1 ");
List<Object> getParamList = new ArrayList<Object>();
createSQLWhereCondition(mysql, getParamList);
GridData<ReportLog> gridData = reportLogService.getPageView(mysql.toString(), getParamList, getPageNum(), getPageSize());
print(ActionUtil.jsonObj(gridData));
} catch (Exception e) {
log.info("获取列表失败");
e.printStackTrace();
}
}
private void createSQLWhereCondition(StringBuilder mysql, List<Object> getParamList) {
if (StringUtils.isNotBlank(userName)) {
mysql.append(" AND c.name LIKE ? ");
getParamList.add("%" + userName + "%");
}
if (StringUtils.isNotBlank(ip)) {
mysql.append(" AND p.ip LIKE ? ");
getParamList.add("%" + ip + "%");
}
if (StringUtils.isNotBlank(mac)) {
mysql.append(" AND p.mac LIKE ? ");
getParamList.add("%" + mac + "%");
}
if (StringUtils.isNotBlank(version)) {
mysql.append(" AND VERSION LIKE ? ");
getParamList.add("%" + version + "%");
}
if (StringUtils.isNotBlank(type)) {
mysql.append(" AND TYPE=?");
getParamList.add(type);
}
if (StringUtils.isNotBlank(startTime)) {
mysql.append("AND TIME >=?");
getParamList.add(startTime);
}
if (StringUtils.isNotBlank(endTime)) {
mysql.append("AND TIME <=?");
getParamList.add(endTime);
}
}
方法getPageView:
@SuppressWarnings("unchecked")
@Override
public GridData<ReportLog> getPageView(String sql, List<Object> getParamList, int pageNum, int pageSize) {
List<Object> paramList = getParamList; // 一、查询总记录数
// a, 生成查询recordCount的Query对象,并设置参数
Query countQuery = this.getSession().createSQLQuery(sql).addEntity(ReportLog.class);
for (int i = 0; i < paramList.size(); i++) {
countQuery.setParameter(i, paramList.get(i));
} // b, 查询出总记录数
int recordCount = countQuery.list().size(); // 计算总页数
int maxPageNum = (recordCount + pageSize - 1) / pageSize;
if (pageNum > maxPageNum)
pageNum = maxPageNum; List<ReportLog> recordlist = null;
if (recordCount > 0) {
// ===============
// 二、查询指定页的数据列表
// a, 生成查询recordList的Query对象,并设置参数
countQuery.setFirstResult((pageNum - 1) * pageSize);
countQuery.setMaxResults(pageSize); // b, 查询出当前页的数据列表
recordlist = countQuery.list();
} return new GridData<ReportLog>(recordCount, recordlist);
}
package com.vrv.paw.bean; import java.io.Serializable;
import java.util.List; /**
* JavaBean:代表UI的一个网格*/
public class GridData<T> implements Serializable {
private static final long serialVersionUID = 1L; /** 总行数 **/
private int total;
/** 行数据 **/
private List<T> rows; public GridData() { } public GridData(int total, List<T> rows) {
this.total = total;
this.rows = rows;
} public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
} }
不仅如此,如果在SQL语句中显示使用了多表连接,则SQL语句可以选出多个数据表的数据。Hibernate还支持将查询结果转换成多个实体。如果要将查询结果转换成多个实体,则SQL字符串中应为不同数据表指定不同别名,并调用addEntity(String alias,Class entityClass)方法将不同数据表转换程不同实体。
public void multiEntityQuery(){
Session session=HibernateUtil.currentSession();
Transaction tx=session.beginTransaction();
String sql="Select s.*,e.*,c.* From student s,enrolment e,course c Where s.id=e.id And e.code=c.code ";
List l=session.createSQLQuery(sql)
.addEntity("s",Student.class)
.addEntity("e",Enrolment.class)
.addEntity("c",Course.class)
.list();
tx.commit();
HibernateUtil.closeSession();
}