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 ...
随机推荐
- [转载] PHP开发必看 编程十大好习惯
适当抽象 但是在抽象的时候,要避免不合理的抽象,有时也可能造成过渡设计,现在只需要一种螺丝刀,但你却把更多类型的螺丝刀都做出来了(而且还是瑞士军刀的样子..): 一致性 团队开发中,可能每个人的编程风 ...
- e643. 以匿名类处理事件
If an event handler is specific to a component (that is, not shared by other components), there is n ...
- 【Java面试题】33 HashMap和Hashtable的区别
1 HashMap不是线程安全的 hastmap是一个接口 是map接口的子接口,是将键映射到值的对象,其中键和值都是对象,并且不能包含重复键,但可以包含重复值.HashMap允许null key和n ...
- 抽象工厂模式(abstract factory pattern)------创造型模式
创建型模式:抽象工厂模式 引入概念: 1.产品等级结构:当抽象的产品由具体的工厂生产出不同的产品时,这些归属与同一类的抽象产品就构成了产品等级结构: 2.产品族:具体的工厂可以生产出来的不同产品就构成 ...
- mongodb php auto increment 自增
mongodb的自增实现根oracle,postgresql是差不多,都是通过计数器来实现的. oracle自增实现: 实例说明oracle序列用法 postgresql自增实现: postgresq ...
- CSS使用学习总结
尽量少使用类,因为可以层叠识别,如: .News h3而不必在h3上加类 <div class=”News”> <h3></h3> <h2></h ...
- R-CNN目标检测的selective search(SS算法)
候选框确定算法 对于候选框的位置确定问题,简单粗暴的方法就是穷举或者说滑动窗口法,但是这必然是不科学的,因为时间和计算成本太高,直观的优化就是假设同一种物体其在图像邻域内有比较近似的特征(例如颜色.纹 ...
- VS2008 Output窗口自动滚动
Output窗口默认是自动滚动的,活动光标始终处于最后一行. 但是有时候因为某些操作可能导致Output窗口的自动滚动停止. 如何恢复自动滚动呢? 使用快捷键操作即可:Ctrl + End
- Swift - UITableView的用法
因为倾向于纯代码编码,所以不太喜欢可视化编程,不过也略有研究,所以项目里面的所有界面效果,全部都是纯代码编写! 终于到了重中之重的tableview的学习了,自我学习ios编程以来,工作中用得最多的就 ...
- LoadRunner监视器
视图 说明 Runtime Graphs 运行时视图 Running Vusers 虚拟用户运行视图 User Delined Data Points 用户自定义数据点视图 Error Statist ...