首先,hibernate中hql是不支持union 或 union all 的;
其次,项目中where 判断条件使用or导致查询缓慢,索引未起作用,故有此需求,同时转换成相应的实体类;
最后,直接上代码:
StringBuffer sql = new StringBuffer("");
sql.append(" select {i.*} ");
sql.append(" from t_user_info i ");
sql.append(" where i.passworld = '" + userPass +"'");
if(null != userName && !"".equals(userName)) {
sql.append(" and i.username = '" + userName +"'");
}
sql.append(" union all ");
sql.append(" select {i.*} ");
sql.append(" from t_user_info i ");
sql.append(" where i.passworld = '" + userPass +"'");
if(null != userName && !"".equals(userName)) {
sql.append(" and i.email = '" + userName +"'");
}
sql.append(" union all ");
sql.append(" select {i.*} ");
sql.append(" from t_user_info i ");
sql.append(" where i.passworld = '" + userPass +"'");
if(null != userName && !"".equals(userName)) {
sql.append(" and i.mobile = '" + userName +"'");
}
List<UserInfo> result = userInfoDao.createSQLQuery(sql.toString(), new UserInfo());
return result;
public List<T> createSQLQuery(String sql,UserInfo userInTfo) {
SQLQuery query = this.getSession().createSQLQuery(sql);
query.addEntity("i",UserInfo.class);
return query.list();
}
private Session getSession() {
return this.sessionFactory.getCurrentSession();
}
注:1. select {a.*} from A a where ... union select {a.*} from A a where...
2. 若是要排序:需要在上面查询中,写出查询字段的列,之后order by ,
(select {a.*},a.time from A a where ...) union (select {a.*},a.time from A a where...) order by time