底层方法封装:模糊查询,姓张的人

查询思路: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();
}
}

方案三:

 @Override
public List<T> findCollectionByConditionNoPage(String condition, final 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);
final String finalHql = hql + condition + orderbyCondition;
//方案一:使用模板调用
// List<T> list = this.getHibernateTemplate().find(finalHql, params);
// return list; //方案三:
List<T> list = this.getHibernateTemplate().execute(new HibernateCallback() { @Override
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query = session.createQuery(finalHql);
if(params != null && params.length > 0){
for (int i = 0; i < params.length; i++) {
query.setParameter(i, params[i]);
}
}
return query.list();
} });
return list;
}

2017.1.11  11:58

第一次回顾 2017.5.14 kangjie

SSH电力项目三 - Dao层、service层查询实现(HQL)的更多相关文章

  1. 为何有DAO与Service层?为何先搞Dao接口在搞DaoImpl实现?直接用不行吗?

    转自 http://blog.sina.com.cn/s/blog_4b1452dd0102wvox.html 我们都知道有了Hibernate后,单独对数据的POJO封装以及XML文件要耗损掉一个类 ...

  2. IDEA下Maven项目搭建踩坑记----2.项目编译之后 在service层运行时找不到 com.dao.CarDao

    项目写的差不多 想运行一下,然后发现运行到Service层的时候报错说找不到Dao层文件 ,纠结半天之后看了下编译好的项目文件,发现mapper文件下边是空的, 于是就百度找一下原因,结果说是IDEA ...

  3. springboot 注册dao层 service 层

    可以使用三种注解来引入DAO层的接口到spring容器中.1.@Mapper,写在每一个DAO层接口上,如下: 2.@MapperScan和@ComponentScan两者之一.前者的意义是将指定包中 ...

  4. facade层,service 层,domain层,dao 层设计

    转自http://fei-6666.iteye.com/blog/446247,记录下来 一,Service->DAO,只能在Service中注入DAO. 二,DAO只能操作但表数据,跨表操作放 ...

  5. 基于Spring4+Hibernate4的通用数据访问层+业务逻辑层(Dao层+Service层)设计与实现!

    基于泛型的依赖注入.当我们的项目中有很多的Model时,相应的Dao(DaoImpl),Service(ServiceImpl)也会增多. 而我们对这些Model的操作很多都是类似的,下面是我举出的一 ...

  6. [转]JAVA中Action层, Service层 ,modle层 和 Dao层的功能区分

    首先这是现在最基本的分层方式,结合了SSH架构.modle层就是对应的数据库表的实体类.Dao层是使用了Hibernate连接数据库.操作数据库(增删改查).Service层:引用对应的Dao数据库操 ...

  7. Action层, Service层 和 Dao层的功能区分

    Action/Service/DAO简介:  Action是管理业务(Service)调度和管理跳转的. Service是管理具体的功能的. Action只负责管理,而Service负责实施. DAO ...

  8. JAVA中Action层, Service层 ,modle层 和 Dao层的功能区分

    Dao层是使用了Hibernate连接数据库.操作数据库(增删改查).Service层:引用对应的Dao数据库操作,在这里可以编写自己需要的代码(比如简单的判断).Action层:引用对应的Servi ...

  9. ssh框架,工具类调用service层方法

    解决方法: @Component//声明为spring组件 public class CopyFileUtil{ @Autowired private DataFileManager dataFile ...

随机推荐

  1. 利用Nginx搭建RTMP视频直播,点播服务器,ffmpeg推流,回看

        一.环境和工具 ubuntu 14.04 desktop 不用server的原因是一部分的演示用到了linux视频播放和直播软件,自己还要装桌面,麻烦. 不建议使用 最新的16TLS,我一开始 ...

  2. PHPstorm8 自动换行设置方法

    PHPstorm是一款非常不错的PHP开发工具,有很多需要自己设置.比如,IDE常见的代码自动换行功能需要我们自己去配置才能实现. File -> Settings ->  Editor ...

  3. CentOS 下 MySQL 5.7 编译安装

    MySQL5.7主要特性: 1—更好的性能:对于多核CPU.固态硬盘.锁有着更好的优化,每秒100W QPS已不再是MySQL的追求,下个版本能否上200W QPS才是吾等用户更关心的 2—更好的In ...

  4. jquery 新建的元素事件绑定问题研究[转]

    原文:http://www.cnblogs.com/linzheng/archive/2010/10/17/1853568.html js的事件监听跟css不一样,css只要设定好了样式,不论是原来就 ...

  5. Python 随机数,break,continue

    #-*- coding:utf-8 -*- #导入模块 import random #打印10以内的随机数 num = 5 while num > 0: #random.randint(0,10 ...

  6. foreach、count、explode(对无限级分类的语法注释-显示无限级效果)

    foreach ($array as $key => $value) foreach仅能用于数组. 每次循环中,当前单元的键名也会在每次循环中被赋给变量$key. 当前单元的值被赋给$value ...

  7. 免费 web api 接口大全

    下面的接口来自互联网,部分功能需要付费 查询手机 http://www.yodao.com/s-martresult-xml/search.s?type=mobile&q= 手机号码 查询 I ...

  8. 【转载】C#基础系列——小话泛型

    前言:前面两章介绍了C#的两个常用技术:C#基础系列——反射笔记 和 C#基础系列——Attribute特性使用 .这一章来总结下C#泛型技术的使用.据博主的使用经历,觉得泛型也是为了重用而生的,并且 ...

  9. (转)c++多态实现的机制

    原文地址:http://blog.csdn.net/zyq0335/article/details/7657465 1 什么是多态?多态性可以简单的概括为“1个接口,多种方法”,在程序运行的过程中才决 ...

  10. php -- PHP在linux上执行外部命令,system(),exec(),shell_exec()

    目录:一.PHP中调用外部命令介绍二.关于安全问题三.关于超时问题四.关于PHP运行linux环境中命令出现的问题 一.PHP中调用外部命令介绍 在PHP中调用外部命令,有三种方法: 1. 调用专门函 ...