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 ...
随机推荐
- 数据导入报错 Got a packet bigger than‘max_allowed_packet’bytes
数据导入报错:Got a packet bigger than‘max_allowed_packet’bytes的问题 2个解决方法: 1.临时修改:mysql>set global max_a ...
- SQLSERVER2008中创建数据库发生无法获得数据库'model'上的排他锁
SQLSERVER2005中创建数据库发生无法获得数据库'model'上的排他锁是怎么回事? 创建数据库失败,提示无法获得数据库‘model’上的排他锁,如下图所示: 解决方法: 在查询分析器中运行如 ...
- DataGridView基本操作
1.获得某个(指定的)单元格的值:dataGridView1.Row[i].Cells[j].Value;2.获得选中的总行数:dataGridView1.SelectedRows.Count;3.获 ...
- 关于Struts2的action的execute方法
这个方法必须要有一个String类型的返回值,所以如果写很多if else的话,记得要在最后加一个else,就是无论如何就会放回一个字符串,否则编译会报错,在execute方法名字下面有红线.
- e658. 组合图形
Area shape = new Area(shape1); shape.add(new Area(shape2)); shape.subtract(new Area(shape3)); shape. ...
- javascript -- addEventListener()和removeEventListener
addEventListener()与removeEventListener()用于处理指定和删除事件处理程序操作.所有的DOM节点中都包含这两种方法,并且它们都接受3个参数:要处理的事件名.作为事件 ...
- IFrame实现的无刷新(仿ajax效果)...
前台代码: <iframe style="display:none;" name="gg"></iframe> <form act ...
- 【Java面试题】53 能不能自己写个类,也叫java.lang.String?
可以,但是即使你写了这个类,也没有用. 这个问题涉及到加载器的委托机制,在类加载器的结构图(在下面)中,BootStrap是顶层父类,ExtClassLoader是BootStrap类的子类,ExtC ...
- PHP开启伪静态配置
1.检测Apache是否开启mod_rewrite功能 可以通过php提供的phpinfo()函数查看环境配置,找到“Loaded Modules”,其中列出了所有apache2handler已经开启 ...
- [Scikit-learn] Dynamic Bayesian Network - Kalman Filter
看上去不错的网站:http://iacs-courses.seas.harvard.edu/courses/am207/blog/lecture-18.html SciPy Cookbook:http ...