欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

hibernate关联查询三

程序员文章站 2022-04-17 08:15:35
...

注意:查询select 后面的字段要有对应的构造函数

public Page<PortalCatalog> getPage(Page page, String name) {
    String sql = "select tc.id,tc.name,tc.url,tc.orderindex,tc.display,tc.orgid,tc.createrid,tp.docTitle from t_portalcatalog_tab tc left join t_portal_tab tp on tc.id=tp.portalCatalogId where 1=1";
    if (null != name && !name.trim().equals("")) {
         sql += " and tc.name like '%"+ StringUtil.sqlValidate(name)+"%'";
         sql += " or tp.docTitle like '%"+ StringUtil.sqlValidate(name)+"%'";
     }
     List<PortalCatalog> list = this.createSQLQuery(sql).addEntity(PortalCatalog.class).list();
     Integer count = getCount(sql);
     page.setTotalCount(count);
     page.setResult(list);
     return page;
}

查询总记录数:

public Integer getCount(String sql){
    return this.countSqlQueryResult(sql.toString());
 }
/**
     * 获取查询记录总数
     * @param sql
     * @param values
     * @return
     */
protected int countSqlQueryResult(String sql, Object... values){
    Matcher m = Pattern.compile("from", Pattern.CASE_INSENSITIVE).matcher(sql);
    m.find();
    int index = m.start();
    StringBuffer sb = new StringBuffer("select count(1) ");
    sb.append(sql.substring(index, sql.length()));
    Query query = createSQLQuery(sb.toString(), values);
    return ((Number) query.uniqueResult()).intValue();
}
/**
	 * SQL方式查询
	 * @param sql 符合SQL语法的查询语句
	 * @param values 数量可变的条件值,按顺序绑定
	 */
public SQLQuery createSQLQuery(final String sql,final Object... values){
     SQLQuery query = getSession().createSQLQuery(sql);
     if (values != null) {
	  for (int i = 0; i < values.length; i++) {
	      query.setParameter(i, values[i]);
	  }
     }
     return query;
}