七、hibernate中的持久层模板操作HibernateTemplate的用法「建议收藏」

七、hibernate中的持久层模板操作HibernateTemplate的用法「建议收藏」利用模板操作来替换掉持久层的session,必须先将spring和hibernate之间进行整合,整合的applicationContext配置文件介绍在:https://blog.csdn.net/IT_CREATE/article/details/86141823 那么在持久层的代码就如下面这样写:1、对于增删改(和session的操作差不多,也有save、update、del…

大家好,又见面了,我是你们的朋友全栈君。

利用模板操作来替换掉持久层的session,必须先将spring和hibernate之间进行整合,整合的applicationContext配置文件介绍在:

https://blog.csdn.net/IT_CREATE/article/details/86141823

 

那么在持久层的代码就如下面这样写:

1、对于增删改(和session的操作差不多,也有save、update、delete三个方法)

@Repository
public class UserDaoImpl implements IUserDao {

	@Resource
	private HibernateTemplate hibernateTemplate;

	@Override
	public void saveUserBean(UserBean user) {
		// TODO Auto-generated method stub
		hibernateTemplate.save(user);
	}

	@Override
	public void updateUserBean(UserBean user) {
		// TODO Auto-generated method stub
		hibernateTemplate.update(user);
	}

	@Override
	public void deleteUserBean(UserBean user) {
		// TODO Auto-generated method stub
		hibernateTemplate.delete(user);
	}
}

2、对于查询(通过id查询数据也有get和load两个方法)

@Repository
public class UserDaoImpl implements IUserDao {

	@Resource
	private HibernateTemplate hibernateTemplate;

	@Override
	public UserBean getUserBeanById(int id) {
		// TODO Auto-generated method stub
		return (UserBean) hibernateTemplate.get(UserBean.class, id);
	}

	@Override
	public UserBean loadUserBeanById(int id) {
		// TODO Auto-generated method stub
		/*
		 * get()和load()的区别: get()在查询对象时,采用的是即时查询方法,它从一级缓存开始,进行二级缓存,到达数据库,它一定会得到一个最终的结果。
		 * load()在查询对象时,采用的是延迟查询方法,它从一级缓存开始,进行二级缓存,如果二级缓存中没有对应的数据,它将默认数据库中一定存在那条数据,
		 * 并返回该对象的代理对象, 直到程序发生调用时,才去查询,找到了就正常返回,找不到,抛异常:ObjectNotFoundException
		 */

		// 延迟加载对象,一定不能关闭Session
		return (UserBean) hibernateTemplate.load(UserBean.class, id);
	}
}

 

下面是自定义查询条件:(具体的查询方法可参考https://www.cnblogs.com/xrab/p/5586775.html

1、利用hql语句进行查询的一些方法

@Repository
public class UserDaoImpl implements IUserDao {

	@Resource
	private HibernateTemplate hibernateTemplate;


	@Override
	public Map<String, Object> queryUserBeanById(Integer id) {
		// TODO Auto-generated method stub
		String hql = "select new map(u.userName as userName,u.loginName as loginName,u.password as password) From UserBean as u where id = ?";
		List<?> datas = hibernateTemplate.find(hql, new Object[] {id});
		if (datas != null)
			return (Map<String, Object>) datas.get(0);
		return null;
	}

	@Override
	public List<?> findUserBeanMapByObject(UserBean user) {
		// TODO Auto-generated method stub
		String hql = "select new map(u.loginName,u.userName,u.age) From UserBean as u where u.userName like concat(:userName,'%') and u.gender = :gender";
		//要求user对象的属性,必须包含HQL中参数名称,“:”后面的名称必须和对象属性一致
		return hibernateTemplate.findByValueBean(hql, user);
	}

	@Override
	public UserBean findUserBeanByLoginNameAndPwd(String loginName, String pwd) {
		// TODO Auto-generated method stub
		/*按照位置进行设值 */
//		  String hql = "From UserBean as u where u.loginName = ? and u.password = ?";
//		  List<?> datas = hibernateTemplate.find(hql, new Object[] {loginName,pwd});
//			if (datas != null) {
//				return (UserBean) datas.get(0);
//			}
//		  return null;
		

		/*
		 * 按照参数别名进行设值
		 */
		String hql = "From UserBean as u where u.loginName = :ln and u.password = :pwd";
		List<?> datas = hibernateTemplate.findByNamedParam(hql, new String[] {"ln","pwd"},new Object[] {loginName,pwd});
		if (datas != null)
			return (UserBean) datas.get(0);
		return null;
	}

	@Override
	public List<?> findUserBeanByObject(UserBean user) {
		// TODO Auto-generated method stub

		// --------------------------------------------------------
		// ----------使用Query完成多条件查询(明显的缺陷:需要拼接语句)--------
		// --------------------------------------------------------
		/*
		 * 
		 * */
		//select 字段列表 from 表 where 条件 
		String hql = "select new UserBean(u.loginName,u.userName,u.age) From UserBean as u where u.userName like concat(:userName,'%') and u.gender = :gender";
		return hibernateTemplate.findByValueBean(hql, user);
		
		 
		String hql = "select new map(u.loginName as loginName,u.userName as userName,u.age as age) From UserBean as u where u.userName like concat(:userName,'%') and u.gender = :gender";
		return hibernateTemplate.findByValueBean(hql, user);	 
	}

	/**
	 *通过Map查询用户数据方法
	 *如果传入的是map,那么map中键的名字必须和hql语句中“:参数名”的参数名一致,才能在预编译后赋值生效。在这里,也就是说,map中有两个键,userName和gender
	 */
	@Override
	public List<?> findUserBeanByMap(Map map) {
		// TODO Auto-generated method stub
		String hql = "select new map(u.loginName as loginName,u.userName as userName,u.age as age) From UserBean as u where u.userName like concat(:userName,'%') and u.gender = :gender";
		return hibernateTemplate.findByValueBean(hql, map);
	}

	/**
	 *得到分页数据方法
	 */
	@SuppressWarnings("all")
	@Override
	public PageBean findUserBeanList2PageBean(PageBean page, UserBean user) {
	
		// --------------------------------------------------------
		// ----------使用Query完成多条件查询(明显的缺陷:需要拼接语句)--------
		// --------------------------------------------------------
		return (PageBean) hibernateTemplate.execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session) throws HibernateException {
				// TODO Auto-generated method stub
				  String hql = "select count(*) from UserBean as u where u.userName like concat(:userName,'%') and u.gender = :gender"; 
				  Query query = session.createQuery(hql); 
				  query.setProperties(user);
				  //uniqueResult()表示返回一个唯一的结果 
				  long totalRows = (long) query.uniqueResult();
				  
				  List<?> datas = null; 
				  if(totalRows > 0) { 
					  hql = "from UserBean as u where u.userName like concat(:userName,'%') and u.gender = :gender"; 
					  query = session.createQuery(hql); 
					  query.setProperties(user);
				  
				  //设置数据库中查询起始位置、获取的数据条数 
				  query.setFirstResult(page.getIndex());
				  query.setMaxResults(page.getRows()); 
				  datas = query.list(); 
				  
				  }
				  page.setTotalRows(totalRows); 
				  page.setData(datas); 
				  return page;
			}
			
		});
	}

}

利用hibernateTemplate.execute方法可以直接操作session,方法内部用到了匿名内部类,这样就和直接操作session一样了。上面的到分页数据中的方法用到的PageBean类在文章尾部。

 

2、利用Criteria进行查询的方法

@Repository
public class UserDaoImpl implements IUserDao {

	@Resource
	private HibernateTemplate hibernateTemplate;

	@Override
	public List<?> findUserBeanByObject(UserBean user) {
		// TODO Auto-generated method stub
		// --------------------------------------------------------
		// --------------使用Criteria完成多条件查询---------------------
		// --------------------------------------------------------
		DetachedCriteria criteria = DetachedCriteria.forClass(UserBean.class);// From UserBean where 1=1
		if (!StringUtils.isEmpty(user.getLoginName())) {
			criteria.add(Restrictions.eq("loginName", user.getLoginName()));// and loginName = '"+user.getLoginName()+"'
		}
		if (!StringUtils.isEmpty(user.getUserName())) {
			criteria.add(Restrictions.like("userName", user.getUserName(), MatchMode.START));// and userName like
		}

		criteria.add(Restrictions.or(Restrictions.eq("gender", 0), Restrictions.eq("gender", 1)));

		criteria.add(Restrictions.between("age", 18, 60));// between …… and ……

		criteria.addOrder(Order.desc("createTime"));// 按照创建时间降序排列
		return hibernateTemplate.findByCriteria(criteria);	 
	}


	@SuppressWarnings("all")
	@Override
	public PageBean findUserBeanList2PageBean(PageBean page, UserBean user) {
		// TODO Auto-generated method stub
		// --------------------------------------------------------
		// --------------使用Criteria完成多条件查询---------------------
		// --------------------------------------------------------
		
		return (PageBean) hibernateTemplate.execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session) throws HibernateException {
				// TODO Auto-generated method stub
				Criteria criteria = session.createCriteria(UserBean.class);
				if (!StringUtils.isEmpty(user.getLoginName())) {
					criteria.add(Restrictions.eq("loginName", user.getLoginName()));// and loginName = '"+user.getLoginName()+"'
				}
				if (!StringUtils.isEmpty(user.getUserName())) {
					criteria.add(Restrictions.like("userName", user.getUserName(), MatchMode.START));// and userName like
				}
				if (user.getGender() != null) {
					criteria.add(Restrictions.eq("gender", user.getGender()));
				}
				if (user.getBirthday() != null) {
					criteria.add(Restrictions.ge("birthday", user.getBirthday()));
				}

				// 添加投影
				criteria.setProjection(Projections.rowCount());// 我在From UserBean之上 添加了一个select count(*)
				
				long totalRows = (long) criteria.uniqueResult();// 获得多少条
				List<?> datas = null;
				if (totalRows > 0) {
					// 去掉投影
					criteria.setProjection(null);
					criteria.setFirstResult(page.getIndex());
					criteria.setMaxResults(page.getRows());
					datas = criteria.list();
				}
				page.setTotalRows(totalRows);
				page.setData(datas);
				return page;
			}
		});
	}

	@Override
	public List<?> findUserBeanByIdcardAndAddress(String idcard, String address) {
		// TODO Auto-generated method stub
		
		// --------------------------------------------------------
		// --------------使用Criteria完成多条件查询---------------------
		// --------------------------------------------------------
		DetachedCriteria criteria = DetachedCriteria.forClass(UserBean.class);//From UserBean as u where 1=1
		//关联对象查询,给关联对象取别名,并且完成两个对象之间的关联
		criteria.createAlias("userInfo", "i",JoinType.LEFT_OUTER_JOIN);
		criteria.createAlias("adds", "a",JoinType.LEFT_OUTER_JOIN);
		
		if(!StringUtils.isEmpty(idcard)) {
			criteria.add(Restrictions.like("i.idcard", idcard,MatchMode.START));
		}
		if(!StringUtils.isEmpty(address)) {
			criteria.add(Restrictions.like("a.address", address,MatchMode.START));
		}
		
		return hibernateTemplate.findByCriteria(criteria);
	}

}

上面代码中的findUserBeanByObject() findUserBeanByIdcardAndAddress()方法中用到了DetachedCriteria类,因为hibernateTemplate.findByCriteria(DetachedCriteria  criteria)方法必须传入DetachedCriteria,

关于DetachedCriteria和Criteria的区别自行查阅。他们的用法差不多,只是DetachedCriteria相比Criteria少了一些方法。

Criteria由session的createCriteria(类.class)方法产生,

DetachedCriteria由它自带的2个静态方法forClass(Class) 或 forEntityName(Name) 进行DetachedCriteria 的实例创建。

 

  • DetachedCriteria中去重复,并且将关联对象装配到主对象,用:  criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
@Override
public List<?> findTeacherBeanByStudentName(String stuName) {
	// TODO Auto-generated method stub
//	String hql = "select DISTINCT(t) From TeacherBean as t left join fetch t.stus as s where s.stuName like concat(:stuName,'%')";
//	return hibernateTemplate.findByNamedParam(hql, "stuName", stuName);
		
		
	DetachedCriteria criteria = DetachedCriteria.forClass(TeacherBean.class);
	criteria.createAlias("stus", "s",JoinType.LEFT_OUTER_JOIN);
	if(!StringUtils.isEmpty(stuName)) {
		criteria.add(Restrictions.like("s.stuName", stuName, MatchMode.START));
	}
		
	//去重复,并且将关联对象,装配到主对象身上去,相当于hql与剧中的DISTINCT()加上fetch的作用
	criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
	return hibernateTemplate.findByCriteria(criteria);
	
}

 

 

下面简单列举两个返回分页数据的例子:

1、利用Criteria

@Repository
public class StudentDaoImpl implements IStudentDao {

	@Resource
	private HibernateTemplate hibernateTemplate;

	@SuppressWarnings("all")
	@Override
	public void findStudentBeanByTeacherName2PageBean(PageBean page, String teacherName) {
		// TODO Auto-generated method stub
		
		hibernateTemplate.execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session) throws HibernateException {
				// TODO Auto-generated method stub
				Criteria criteria = session.createCriteria(StudentBean.class);
				criteria.createAlias("teacher", "t",JoinType.LEFT_OUTER_JOIN);
				if(!StringUtils.isEmpty(teacherName)) {
					criteria.add(Restrictions.like("t.teacherName", teacherName, MatchMode.START));
				}
				
				//添加投影
				criteria.setProjection(Projections.rowCount());
				long totalRows = (long) criteria.uniqueResult();
				List<?> datas = null;
				if(totalRows > 0) {
					criteria.setProjection(null);
					criteria.setFirstResult(page.getIndex());
					criteria.setMaxResults(page.getRows());
					criteria.setResultTransformer(Criteria.ROOT_ENTITY);//这句话的作用  === HQL中编写的fetch
					datas = criteria.list();
				}
				page.setTotalRows(totalRows);
				page.setData(datas);
				return page;
			}
		});
	}

}

2、利用hql

@Repository
public class StudentDaoImpl implements IStudentDao {

	@Resource
	private HibernateTemplate hibernateTemplate;

	@SuppressWarnings("all")
	@Override
	public void findStudentBeanByTeacherName2PageBean(PageBean page, String teacherName) {
		// TODO Auto-generated method stub
		
		
		hibernateTemplate.execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session) throws HibernateException {
				// TODO Auto-generated method stub
				String hql = "select count(*) From StudentBean as s left join s.teacher as t where t.teacherName like concat(:teacherName,'%')";
				Query query = session.createQuery(hql);
				query.setString("teacherName", teacherName);
				long totalRows = (long) query.uniqueResult();
				List<?> datas = null;
				if(totalRows > 0) {
					hql = "From StudentBean as s left join fetch s.teacher as t where t.teacherName like concat(:teacherName,'%')";
					query = session.createQuery(hql);
					query.setString("teacherName", teacherName);
					query.setFirstResult(page.getIndex());
					query.setMaxResults(page.getRows());
					datas = query.list();
				}
				page.setTotalRows(totalRows);
				page.setData(datas);
				return page;
			}
		});
		
	}

}

 

PageBean类:

package com.ge.hibernatexml.bean;

import java.util.List;

/**
 * 分页对象
 * @author Administrator
 *
 */
public class PageBean {

	private int page;//当前页码
	private int rows;//每页显示数据的行数
	
	private int index;//数据获取的起始位置(数据库中)
	private long totalRows;//数据总条数
	private long totalPage;//总共有多少页
	
	private String sort;//排序字段
	private String order;//排序方式
	
	//具体的数据
	private List<?> data;

	
	public PageBean() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public PageBean(int page, int rows) {
		super();
		this.page = page;
		this.rows = rows;
		//计算数据获取的起始位置
		this.index = (page - 1) * rows;
	}


	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	public long getTotalRows() {
		return totalRows;
	}

	public void setTotalRows(long totalRows) {
		this.totalRows = totalRows;
		//总页码
		this.totalPage = totalRows % rows == 0 ? totalRows / rows : totalRows / rows + 1;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public long getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(long totalPage) {
		this.totalPage = totalPage;
	}

	public List<?> getData() {
		return data;
	}

	public void setData(List<?> data) {
		this.data = data;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", index=" + index + ", totalRows=" + totalRows
				+ ", totalPage=" + totalPage + ", sort=" + sort + ", order=" + order + ", data=" + data + "]";
	}
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/149770.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • windows下载安装adb(极其简单)

    windows下载安装adb(极其简单)单独安装adb,不安装sdk下载adbGoogle很好的心,直接放出ADB的档案供人下载。下档路径如下:Windows版本:https://dl.google.com/android/repository/platform-tools-latest-windows.zipMac版本:https://dl.google.com/android/repository/platform-tools-latest-windows.zipLinux版本:https://dl.google.com/andro

  • js读取本地json文件_jquery读取本地json文件

    js读取本地json文件_jquery读取本地json文件1.首先编写一个json文件:demo.json[{“name”:”张三”,”sex”:”男”,”email”:”zhangsan@123.com”},{“name”:”李四”,”sex”:”男”,”email”:”lisi@123.com”},{“name”:”王五”,”sex”:”女”,”email”:”wangwu@123.com…

    2022年10月12日
  • android线程通信的几种方式_java多线程的实现方式

    android线程通信的几种方式_java多线程的实现方式1,通过Handler机制.privatevoidone(){handler=newHandler(){@OverridepublicvoidhandleMessage(Messagemsg){super.handleMessage(msg);

  • MySQL官网下载太慢的解决方法

    MySQL官网下载太慢的解决方法今天重新配置了服务器,所有环境都搭建好了,万事具备,只欠MySql,于是去官网找了5.7版本的下下来。可是画风是这样的,有点跨。。。在网站查了半天,也没有找到好的解决办法,捣鼓了半天,终于搞定了,下面说下解决方法。第一步,进入官网,选择需要下载的版本,我选择的是Linux通用版5.7,点击Download第二步,按F12,有些电脑是Fn+F12,查看下载地址第三步,复…

  • python中list与string的转换「建议收藏」

    python中list与string的转换「建议收藏」1.list转string命令:”.join(list)其中,引号中是字符之间的分割符,如“,”,“;”,“\t”等等如:list=[1,2,3,4,5]”.join(list)结果即为:12345′,’.join(list)结果即为:1,2,3,4,5str=[]#有的题目要输出字符串,但是有时候list更好操作,于是可以最后list转st…

  • java程序一定会加载的包是哪个?

    java程序一定会加载的包是哪个?

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号