底层方法封装:模糊查询,姓张的人
查询思路:select * from elec_text o #Dao层
where o.textName like '%张%' #Service层
and o.textRemark like '%张%' #Service层
order by o.textDate ASC, o.textName DESC ; #Service层
为了在业务层对称,采用如下写法:
select * from elec_text o where 1=1 #Dao层
and o.textName like '%张%' #Service层
and o.textRemark like '%张%' #Service层
order by o.textDate ASC, textName DESC #Service层
TestService.java
package junit;
public class TestService { @Test public void save(){ ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml"); IElecTextService elecTextService = (IElecTextService) ac.getBean(IElecTextService.SERVICE_NAME); ElecText e = new ElecText(); e.setTextName("abbbc"); e.setTextDate(new Date()); e.setTextRemark("deeef"); elecTextService.saveElecText(e); }
// @Test public void findCollectionByConditionNopage(){ ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml"); IElecTextService elecTextService = (IElecTextService) ac.getBean(IElecTextService.SERVICE_NAME); ElecText elecText = new ElecText(); elecText.setTextName("张"); elecText.setTextRemark("张"); List<ElecText> list = elecTextService.findCollectionByConditionNopage(elecText); if(list != null && list.size() > 0){ for(ElecText text:list){ System.out.println(text.getTextName() + "+"+ text.getTextRemark()); } } } }
ElecTextService.java 接口:
package com.itheima.elec.service;public interface IElecTextService { public static final String SERVICE_NAME="com.itheima.elec.service.impl.ElecTextServiceImpl"; void saveElecText(ElecText elecText); List<ElecText> findCollectionByConditionNopage(ElecText elecText); }
ElecTextServiceImpl.java 接口
package com.itheima.elec.service.impl; //事务控制:spring的声明事务处理,在service层添加@Transactional @Service(IElecTextService.SERVICE_NAME) @Transactional(readOnly=true) public class ElecTextServiceImpl implements IElecTextService { @Resource(name=IElecTextDao.SERVICE_NAME) IElecTextDao elecTextDao; @Transactional(readOnly=false) public void saveElecText(ElecText elecText) { // TODO Auto-generated method stub elecTextDao.save(elecText); } @Override public List<ElecText> findCollectionByConditionNopage(ElecText elecText) { //查询条件 String condition = ""; //查询条件对应的参数 List<Object> paramsList = new ArrayList<Object>(); // if(elecText.getTextName() != null && !elecText.getTextName().equals("")){ // condition += " and o.textName like ?"; // } if(StringUtils.isNotBlank(elecText.getTextName())){ condition += " and o.textName like ?"; paramsList.add("%" + elecText.getTextName() + "%"); } if(StringUtils.isNotBlank(elecText.getTextRemark())){ condition += " and o.textRemark like ?"; paramsList.add("%" + elecText.getTextRemark() + "%"); } //传递可变参数 Object [] params = paramsList.toArray(); //排序 Map<String, String> orderby = new LinkedHashMap<String,String>(); orderby.put("o.textDate", "asc"); orderby.put("o.textName", "desc"); //查询 List<ElecText> list = elecTextDao.findCollectionByConditionNoPage(condition,params,orderby); return list; } }
ICommonDao.java
package com.itheima.elec.dao;public interface ICommonDao<T> { void save(T entity); void update(T entity); T findObjectById(Serializable id); void deleteObjectByIds(Serializable... ids); void deleteObjectByCollection(List<T> list); List<T> findCollectionByConditionNoPage(String condition, Object[] params, Map<String, String> orderby ); }
ICommonDaoImpl.java
package com.itheima.elec.dao.impl;public class CommonDaoImpl<T> extends HibernateDaoSupport implements ICommonDao<T> { //泛型转化 Class entityClass = TUtils.getActualType(this.getClass()); /** * 如何来实现这个save方法:通过HibernateDaoSupport 来实现,需要注入sessionFactory */ @Resource public void setDi(SessionFactory sessionFactory){ this.setSessionFactory(sessionFactory); } @Override public void save(T entity) { this.getHibernateTemplate().save(entity); } public void update(T entity){ this.getHibernateTemplate().update(entity); } @Override public T findObjectById(Serializable id) { // Class entityClass = TUtils.getActualType(this.getClass()); return (T) this.getHibernateTemplate().get(entityClass, id); //entityClass 此处需要类型 } @Override public void deleteObjectByIds(Serializable... ids) { if(ids != null && ids.length > 0){ for(Serializable id:ids){ Object entity = this.findObjectById(id); this.getHibernateTemplate().delete(entity); } } // this.getHibernateTemplate().delete(entity); } @Override public void deleteObjectByCollection(List<T> list) { this.getHibernateTemplate().deleteAll(list); } @Override /** 这里1=1的目的是方便在Service层拼装sql或者hql语句,连接统一使用and * SELECT o FROM ElecText o WHERE 1=1 #Dao层填写 AND o.textName LIKE '%张%' #Service拼装 AND o.textRemark LIKE '%张%' #Service拼装 ORDER BY o.textDate ASC,o.textName desc #Service拼装 */ public List<T> findCollectionByConditionNoPage(String condition, Object[] params, Map<String, String> orderby) { //hql语句 String hql = "from " + entityClass.getSimpleName() + " o where 1 = 1"; //将Map集合中存放的字段排序,组织成ORDER BY o.textDate ASC, o.textName Desc String orderByCondition = this.orderByHql(orderby); //添加查询条件 String finalHql = hql + condition + orderByCondition; //查询,执行sql语句 //方法一: List<T> list = this.getHibernateTemplate().find(finalHql, params);
/*
//方案三
List<T> list = (List<T>) this.getHibernateTemplate().execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException, SQLException {
//回调session
Query query = session.createQuery(finalHql);
if(params!=null && params.length > 0){ //params报错,将传递的参数强转为final 类型
for(int i=0;i<params.length;i++){
query.setParameter(i, params[i]);
}
}
return query.list();
}
});
*/ return list; } private String orderByHql(Map<String, String> orderby) { StringBuffer buffer = new StringBuffer(""); if(orderby != null && orderby.size() > 0){ buffer.append(" ORDER BY "); //这个地方一定要加空格,否则拼接字符串会报错 for(Map.Entry<String, String> map:orderby.entrySet()){ buffer.append(map.getKey() + " " + map.getValue() + ","); } //删除最后一个逗号 buffer.deleteCharAt(buffer.length() - 1); } return buffer.toString(); } }
方案三:
1 @Override 2 public List<T> findCollectionByConditionNoPage(String condition, final Object[] params, Map<String, String> orderby) { 3 //hql语句 面向对象 4 String hql="from "+ entityClass.getSimpleName() +" o where 1=1"; 5 //添加查询条件 6 //将map集合中存放的字段排序组织成字符串 order by o.textDate asc, o.textName desc 7 String orderbyCondition = this.orderbyHql(orderby); 8 final String finalHql = hql + condition + orderbyCondition; 9 //方案一:使用模板调用 10 // List<T> list = this.getHibernateTemplate().find(finalHql, params); 11 // return list; 12 13 //方案三: 14 List<T> list = this.getHibernateTemplate().execute(new HibernateCallback() { 15 16 @Override 17 public Object doInHibernate(Session session) throws HibernateException, SQLException { 18 Query query = session.createQuery(finalHql); 19 if(params != null && params.length > 0){ 20 for (int i = 0; i < params.length; i++) { 21 query.setParameter(i, params[i]); 22 } 23 } 24 return query.list(); 25 } 26 27 }); 28 return list; 29 }
2017.1.11 11:58
第一次回顾 2017.5.14 kangjie