SSH电力项目三 - Dao层、service层查询实现(HQL)
底层方法封装:模糊查询,姓张的人
查询思路: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)的更多相关文章
- 为何有DAO与Service层?为何先搞Dao接口在搞DaoImpl实现?直接用不行吗?
转自 http://blog.sina.com.cn/s/blog_4b1452dd0102wvox.html 我们都知道有了Hibernate后,单独对数据的POJO封装以及XML文件要耗损掉一个类 ...
- IDEA下Maven项目搭建踩坑记----2.项目编译之后 在service层运行时找不到 com.dao.CarDao
项目写的差不多 想运行一下,然后发现运行到Service层的时候报错说找不到Dao层文件 ,纠结半天之后看了下编译好的项目文件,发现mapper文件下边是空的, 于是就百度找一下原因,结果说是IDEA ...
- springboot 注册dao层 service 层
可以使用三种注解来引入DAO层的接口到spring容器中.1.@Mapper,写在每一个DAO层接口上,如下: 2.@MapperScan和@ComponentScan两者之一.前者的意义是将指定包中 ...
- facade层,service 层,domain层,dao 层设计
转自http://fei-6666.iteye.com/blog/446247,记录下来 一,Service->DAO,只能在Service中注入DAO. 二,DAO只能操作但表数据,跨表操作放 ...
- 基于Spring4+Hibernate4的通用数据访问层+业务逻辑层(Dao层+Service层)设计与实现!
基于泛型的依赖注入.当我们的项目中有很多的Model时,相应的Dao(DaoImpl),Service(ServiceImpl)也会增多. 而我们对这些Model的操作很多都是类似的,下面是我举出的一 ...
- [转]JAVA中Action层, Service层 ,modle层 和 Dao层的功能区分
首先这是现在最基本的分层方式,结合了SSH架构.modle层就是对应的数据库表的实体类.Dao层是使用了Hibernate连接数据库.操作数据库(增删改查).Service层:引用对应的Dao数据库操 ...
- Action层, Service层 和 Dao层的功能区分
Action/Service/DAO简介: Action是管理业务(Service)调度和管理跳转的. Service是管理具体的功能的. Action只负责管理,而Service负责实施. DAO ...
- JAVA中Action层, Service层 ,modle层 和 Dao层的功能区分
Dao层是使用了Hibernate连接数据库.操作数据库(增删改查).Service层:引用对应的Dao数据库操作,在这里可以编写自己需要的代码(比如简单的判断).Action层:引用对应的Servi ...
- ssh框架,工具类调用service层方法
解决方法: @Component//声明为spring组件 public class CopyFileUtil{ @Autowired private DataFileManager dataFile ...
随机推荐
- npm常用命令汇总
npm是一个node包管理和分发工具,已经成为了非官方的发布node模块(包)的标准. 有了npm,可以很快的找到特定服务要使用的包,进行下载.安装以及管理已经安装的包. 1.npm install ...
- jquery javascript 回到顶部功能
今天搞了一个回到顶部的JS JQ功能 (function($){ $.fn.survey=function(options){ var defaults={width:"298", ...
- 聊聊Javascript中的AOP编程
Duck punch 我们先不谈AOP编程,先从duck punch编程谈起. 如果你去wikipedia中查找duck punch,你查阅到的应该是monkey patch这个词条.根据解释,Mon ...
- HTML5之IndexedDB使用详解
随着firefox4正式版的推出,IndexedDB正式进入我们的视线.IndexedDB是HTML5-WebStorage的重要一环,是一种轻量级NOSQL数据库.相较之下,WebDataBase标 ...
- altium designer应用技巧---cyclone IV代芯片底部焊盘问题
首先对于 altera 公司的FPGA芯片来讲,在cyclone III代以上,芯片的底部增加了一 个焊盘,很多工程师往往以为是散热用,其实不然,底部焊盘需要接地(altera手册上面 明确规定,Th ...
- 【转】WCF入门教程五[WCF的通信模式]
一.概述 WCF在通信过程中有三种模式:请求与答复.单向.双工通信.以下我们一一介绍. 二.请求与答复模式 描述: 客户端发送请求,然后一直等待服务端的响应(异步调用除外),期间处于假死状态,直到服务 ...
- par函数pch参数-控制点的形状
pch函数用来控制点的形状,这个参数不仅在par函数中有,在大多数的高级绘图函数中都有. 代码示例: plot(rep(1:5, times = 5), rep(5:1, each = 5), pch ...
- Python使用paramiko库远程安全连接SSH
#!/usr/bin/python #ssh import paramiko import sys,os host='127.0.0.1' user = 'whl' password = ' s = ...
- ubuntu server install 安装中文(搜狗)输入法
1.对于ubuntu server默认无中文输入法框架,我比较倾向于我一直使用的ibus-sunpinyin.这里我需要先安装ibus的框架 不过我遇到了问题: dpkg: dependency pr ...
- shell脚本中特定符合变量的含义
shell脚本中特定符合变量的含义: $# 传递到脚本的参数个数 $* 以一个单字符串显示所有向脚本传递的参数.与位置变量不同,此选项参数可超过9个 $$ 脚本运行的当前进程PID号 ...