hibernate4.1.7 查询使用?占位符的问题 本帖最后由 tangxusc 于 2012-11-29 20:04:08 编辑 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 参数是动态指定和是否":parameters"不矛盾吧,可以这样用 where "+x+"+" =: "+"+x+" 遇到同样的问题,是不是Hibernate4不建议使用索引参数了,看意思像是建议使用名称点位符...Positional parameter are considered deprecated; use named parameters or JPA-style positional parameters instead 你参数可以传map进来啊...为啥一定要list. 这种共通方式,我从来没用过,从技术角度来想,确实省事儿了许多,但是满足了多少业务?很多select都会设计到order by呀,group by呀什么的。。你能确定这些能共通么? package com.dao;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.annotation.Resource;import javax.persistence.Entity;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.springframework.stereotype.Repository;@Repository("daoTemplate")public abstract class DaoTemplate<T> implements Dao<T> { protected SessionFactory sessionFactory = null; @SuppressWarnings("unchecked") public List<T> list(Map<String,Object> parameters, int beginQuery, int maxResult,LinkedHashMap<String, String> orderBy,Class<T> clazz) { String hql="from "+this.getClassName(clazz); // from user| if(parameters!=null&¶meters.size()>0){ hql+=buildWhere(parameters); } // from user where id=:id if(orderBy!=null&&!orderBy.isEmpty()){ hql=hql+this.buildOrderBy(orderBy); }//System.out.println("List-hql:"+hql); // from user where id=1 order by id asc,name desc Session session =sessionFactory.getCurrentSession(); Query query=session.createQuery(hql); query=this.setQueryParameters(query, parameters); if(beginQuery>=0&&maxResult>=0){ query.setFirstResult(beginQuery).setMaxResults(maxResult); } return query.list(); } public boolean add(T entity){ Session session = sessionFactory.getCurrentSession(); if (session.save(entity) != null) { return true; } return false; } public boolean delete(T entity){ try { Session session = sessionFactory.getCurrentSession(); session.delete(entity); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public abstract T get(T entity); @SuppressWarnings("unchecked") public List<T> list(Class<T> clazz){ Session session = sessionFactory.getCurrentSession(); Query query=session.createQuery("from "+this.getClassName(clazz)); return query.list(); } @SuppressWarnings("unchecked") public List<T> list(Map<String,Object> parameters,Class<T> clazz){ String hql="from "+this.getClassName(clazz)+" "; // from user |order by if(parameters!=null&¶meters.size()>0){ hql+=buildWhere(parameters); } Session session =sessionFactory.getCurrentSession(); Query query=session.createQuery(hql); query=this.setQueryParameters(query, parameters); return query.list(); } public boolean update(T entity){ try { Session session = sessionFactory.getCurrentSession();// session.merge(entity); session.update(entity); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public long allCount(Map<String,Object> parameters,Class<T> clazz){ String hql="select count(*) from "+this.getClassName(clazz); //select count(*) form if(parameters!=null&¶meters.size()>0){ hql+=buildWhere(parameters); }//System.out.println("session:"+sessionFactory.getClass()); Session session =sessionFactory.getCurrentSession(); Query query=session.createQuery(hql);//System.out.println("allCount-hql:"+hql); query=this.setQueryParameters(query, parameters); return (Long) query.uniqueResult(); } /** * 获取实体类名(实体名称可能为@Entity("instanceof")) * @param clazz * @return */ private String getClassName(Class<T> clazz){ Entity entity=clazz.getAnnotation(Entity.class); if(entity.name()!=null&&!entity.name().equals("")){ return entity.name(); } String className=clazz.getSimpleName(); return className; } /** * 生成orderBy子句 * @param orderBy * @return order by id asc,name desc */ private String buildOrderBy(LinkedHashMap<String, String> orderBy) { StringBuffer orderByBuffer=new StringBuffer(); orderByBuffer.append(" order by "); for(String key:orderBy.keySet()){ orderByBuffer.append(key).append(" ").append(orderBy.get(key)).append(","); } orderByBuffer.deleteCharAt(orderByBuffer.length()-1);//System.out.println(orderByBuffer.toString()); return orderByBuffer.toString(); } /** * 生成where子句 * @param parameters * @return where子句 */ private String buildWhere(Map<String, Object> parameters) { //<"id",1> StringBuffer where=new StringBuffer(); if(parameters!=null&¶meters.size()>0){ where.append(" where "); for(String key:parameters.keySet()){ //key="parentProductType.id is :id" where.append(key).append(" and "); //where parentProductType.id=:id and | } } where.delete(where.length()-5, where.length());//System.out.println("where:"+where); return where.toString(); } /** * 设置参数值 * @param query * @param parameters * @return */ private Query setQueryParameters(Query query,Map<String, Object> parameters){ if (parameters!=null&¶meters.size()> 0) { //key id=:id enable=:enable //int begin=0; for(String key:parameters.keySet()){ //where id=:id and enable=:enable Pattern pattern = Pattern.compile(":\\w+"); Matcher matcher = pattern.matcher(key); if(matcher.find()){//System.out.println(matcher.group(0)); query.setParameter(matcher.group(0).substring(1, matcher.group(0).length()),parameters.get(key)); } } } return query; } @Override @Resource(name="sessionFactory") public void setSessionFactory(SessionFactory sessionFactory){ this.sessionFactory=sessionFactory; } public SessionFactory getSessionFactory() { return sessionFactory; } } 没问题这个,只是hibernate不建议这样 hibernate4 新点位是?0 ?1,或是 :param,旧的方式有警告了 肿么换成?0 ?1,或是 :param还是换同样错误 求一条HQL查询语句。 关于页面取得日期的问题 关于clientHeight的问题 问个关于j2ee设计模式的问题 使用dom4j解析和保存xml时,为什么会解析出错,多写一些字符进去? javamail无法连接host:127.0.0.1 的问题 请教大家一个关于context的问题 提问:这个html页面它是怎么实现动态的? 求助!!!我做的可以拖动的div,但是拖动之后速度很慢 怎样生成图片验证码? 在线等~~~~怎么在jsp页面新建一个按钮,点击后将页面中的table数据导出到excel中? install4j 做服务
参数是动态指定和是否":parameters"不矛盾吧,可以这样用 where "+x+"+" =: "+"+x+"
Positional parameter are considered deprecated; use named parameters or JPA-style positional parameters instead
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;import javax.annotation.Resource;
import javax.persistence.Entity;import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
@Repository("daoTemplate")
public abstract class DaoTemplate<T> implements Dao<T> {
protected SessionFactory sessionFactory = null; @SuppressWarnings("unchecked")
public List<T> list(Map<String,Object> parameters, int beginQuery,
int maxResult,LinkedHashMap<String, String> orderBy,Class<T> clazz) {
String hql="from "+this.getClassName(clazz); // from user|
if(parameters!=null&¶meters.size()>0){
hql+=buildWhere(parameters);
} // from user where id=:id
if(orderBy!=null&&!orderBy.isEmpty()){
hql=hql+this.buildOrderBy(orderBy);
}
//System.out.println("List-hql:"+hql); // from user where id=1 order by id asc,name desc
Session session =sessionFactory.getCurrentSession();
Query query=session.createQuery(hql);
query=this.setQueryParameters(query, parameters);
if(beginQuery>=0&&maxResult>=0){
query.setFirstResult(beginQuery).setMaxResults(maxResult);
}
return query.list();
} public boolean add(T entity){
Session session = sessionFactory.getCurrentSession();
if (session.save(entity) != null) {
return true;
}
return false;
} public boolean delete(T entity){
try {
Session session = sessionFactory.getCurrentSession();
session.delete(entity);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} public abstract T get(T entity); @SuppressWarnings("unchecked")
public List<T> list(Class<T> clazz){
Session session = sessionFactory.getCurrentSession();
Query query=session.createQuery("from "+this.getClassName(clazz));
return query.list();
} @SuppressWarnings("unchecked")
public List<T> list(Map<String,Object> parameters,Class<T> clazz){
String hql="from "+this.getClassName(clazz)+" "; // from user |order by
if(parameters!=null&¶meters.size()>0){
hql+=buildWhere(parameters);
}
Session session =sessionFactory.getCurrentSession();
Query query=session.createQuery(hql);
query=this.setQueryParameters(query, parameters);
return query.list();
} public boolean update(T entity){
try {
Session session = sessionFactory.getCurrentSession();
// session.merge(entity);
session.update(entity);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long allCount(Map<String,Object> parameters,Class<T> clazz){
String hql="select count(*) from "+this.getClassName(clazz); //select count(*) form
if(parameters!=null&¶meters.size()>0){
hql+=buildWhere(parameters);
}//System.out.println("session:"+sessionFactory.getClass());
Session session =sessionFactory.getCurrentSession();
Query query=session.createQuery(hql);
//System.out.println("allCount-hql:"+hql);
query=this.setQueryParameters(query, parameters);
return (Long) query.uniqueResult();
}
/**
* 获取实体类名(实体名称可能为@Entity("instanceof"))
* @param clazz
* @return
*/
private String getClassName(Class<T> clazz){
Entity entity=clazz.getAnnotation(Entity.class);
if(entity.name()!=null&&!entity.name().equals("")){
return entity.name();
}
String className=clazz.getSimpleName();
return className;
}
/**
* 生成orderBy子句
* @param orderBy
* @return order by id asc,name desc
*/
private String buildOrderBy(LinkedHashMap<String, String> orderBy) {
StringBuffer orderByBuffer=new StringBuffer();
orderByBuffer.append(" order by ");
for(String key:orderBy.keySet()){
orderByBuffer.append(key).append(" ").append(orderBy.get(key)).append(",");
}
orderByBuffer.deleteCharAt(orderByBuffer.length()-1);
//System.out.println(orderByBuffer.toString());
return orderByBuffer.toString();
}
/**
* 生成where子句
* @param parameters
* @return where子句
*/
private String buildWhere(Map<String, Object> parameters) { //<"id",1>
StringBuffer where=new StringBuffer();
if(parameters!=null&¶meters.size()>0){
where.append(" where ");
for(String key:parameters.keySet()){ //key="parentProductType.id is :id"
where.append(key).append(" and "); //where parentProductType.id=:id and |
}
}
where.delete(where.length()-5, where.length());
//System.out.println("where:"+where);
return where.toString();
}
/**
* 设置参数值
* @param query
* @param parameters
* @return
*/
private Query setQueryParameters(Query query,Map<String, Object> parameters){
if (parameters!=null&¶meters.size()> 0) { //key id=:id enable=:enable
//int begin=0;
for(String key:parameters.keySet()){ //where id=:id and enable=:enable
Pattern pattern = Pattern.compile(":\\w+");
Matcher matcher = pattern.matcher(key);
if(matcher.find()){
//System.out.println(matcher.group(0));
query.setParameter(matcher.group(0).substring(1, matcher.group(0).length()),parameters.get(key));
}
}
}
return query;
}
@Override
@Resource(name="sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory=sessionFactory;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
}