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

查询思路: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. Cygwin镜像使用帮助

    Cygwin镜像使用帮助 收录架构 x86 x86_64 收录版本 所有版本 更新时间 每12小时更新一次   使用说明 选择从互联网安装, 在"User URL"处输入以下地址 ...

  2. 30个实用的jQuery选项卡/导航教程推荐

    很多网站设计中都使用了选项卡(tabs),在制作选项卡时应用jQuery能够实现很多炫酷的过渡和动画效果.本文为你介绍30个实用的jQuery选项卡教程,希望对你有帮助. 1. Animated Ta ...

  3. C#NetRemoting双向通信

    闲来无事想玩玩双向通信,实现类似QQ的互发消息的功能.于是乎开始学习.Net Remoting. .Net Remoting 是由客户端通过Remoting,访问通道以获得服务端对象,再通过代理解析为 ...

  4. 【C#】【MySQL】C# 查询数据库语句@Row:=@Row+1以及执行存储过程失败解决方案

    如何实现数据库查询产生虚拟的一列序号的功能: ) )AS r; 该语句可以实现产生虚拟的一列数据在MySQL中运行没有问题. 但是在C#里面调用去出现了错误"Parameter '@ROW' ...

  5. C++ 继承、函数重载

    题外话1:浪费了两天,可耻! 题外话2:你这个年纪,做得好是理所当然,做不好是罪孽深重!!! --- 深以为然. 题外话3:从开始看C++ Primer 到现在,整整24天了,没想到基础方面耗费这么久 ...

  6. 第三百一十节,Django框架,模板语言

    第三百一十节,Django框架,模板语言 模板语言就是可以将动态数据在html模板渲染的语言 一.接收值渲染 locals()函数,写在请求响应render()函数里,可以将逻辑处理函数里的变量传到h ...

  7. JavaScript 学习笔记(二)

    学习内容: 一.变量的定义 二.JS的基本数据类型 三.JS的基本语法 1.变量的定义:   任何语言中最基本的东西就属于变量了,那么如何定义变量以及运用,其实是一件很简单的事情.. JS中提供了如何 ...

  8. MySQL Date函数的正确用法

    以下的文章主要介绍的是MySQL Date函数的实际应用其中包括如何获取当前时间的具体操作,Unix时间的具体应用,时间前后.时间间隔与时间转换的实际内容描述,以下就是文章的主要内容. MySQL D ...

  9. 【Java面试题】45 什么是java序列化,如何实现java序列化?或者请解释Serializable接口的作用。

    我们有时候将一个java对象变成字节流的形式传出去或者从一个字节流中恢复成一个java对象,例如,要将java对象存储到硬盘或者传送给网络上的其他计算机,这个过程我们可以自己写代码去把一个java对象 ...

  10. Linux shell 学习

    ·详细介绍Linux shell脚本基础学习(一) ·详细介绍Linux shell脚本基础学习(二) ·详细介绍Linux shell脚本基础学习(三) ·详细介绍Linux shell脚本基础学习 ...