JavaEE框架——hibernate的使用(关于hibernate事务的必须开启的问题)

一、与数据库的交互(增删改查)

注意:1.写hql语言是是对于对象操作,而不是表数据

            2.注意hibernate中的缓存

1.Hibernate 查询方式

     Hibernate配备了一种非常强大的查询语言,这种语言看上去很像SQL。但是不要被语法结构上的相似所迷惑,HQL(Hibernate querylauguage)被设计为完全面向对象的查询。   

     HQL对关键字的大写小并不区分,但是对查询的对象就要区分大小写,因为它是面向对象的查询,所以查询的是一个对象,而不是数据库的表,在sql中如果要加条件的话就是列,而在HQL里面条件就是对象的属性,而且还要给对象起别名

1.Hibernate 查询 HQL 语句

限制查询结果记录数与起始记录

Sessionsession=HibernateSessionFactory.getSession();

Queryquery=session.createQuery("fromCustomer");

query.setFirstResult(10); //设置查询记录开始位置,索引从0开始。

query.setMaxResults(10);//设置查询返回的最大记录个数。

Listlist=query.list();

注意:条件查询

Sessionsession=HibernateSessionFactory.getSession();

Queryquery=session.createQuery("from Customer cus where cus.name='zhou'");

 2、取表中部分列时

(1) 单一属性查询。还是返回一个集合,只不过集合中存储的不是表的实例而是对象。

Sessionsession =null;

session= HibernateSessionFactory.getSession();

Listcnames = session.createQuery("select cname from Customer").list();

for(inti=0;i<cnames.size();i++) {

  String name = (String)cnames.get(i);

  System.out.println(name);

}

(2) 多个属性的查询,使用对象数组。

Sessionsession =null;

session= HibernateSessionFactory.getSession();

//查询多个属性,其集合元素是对象数组

//数组元素的类型,跟实体类的属性的类型相关

Liststudents = session.createQuery("select sno,sname from Students").list();

for(inti=0;i<students.size();i++) {

  Object[] obj = (Object[])students.get(i);

  System.out.println(obj[0] +", " + obj[1]);

}

 (3) 多个属性的查询,使用List集合装部分列

Sessionsession = HibernateSessionFactory.getSession();

Queryquery = session.createQuery("select new list(cus.name,cus.phone) from Customer cus");

Listlist = query.list();

for(int i = 0; i < list.size(); i++) {

  List temp=(List)list.get(i);

  System.out.println(temp.get(0));  //0是索引

}

 (4) 使用Map集合装部分列

Sessionsession = HibernateSessionFactory.getSession();

Queryquery = session.createQuery("select new map(cus.name,cus.phone) from Customer cus");

Listlist = query.list();

for(int i = 0; i < list.size(); i++) {

  Map temp=(Map)list.get(i);

  System.out.println(temp.get("1"));  //"1"是key
}

 3、内连接  

Queryquery=session.createQuery("select c.name, s.name fromStudent s join s.classes c").list();

for(Iterator iter = students.iterator();iter.hasNext();){

  Object[] obj = (Object[])iter.next();

  System.out.println(obj[0] +", " + obj[1]);

}

4、外连接

Queryquery=session.createQuery("select c.name, s.name fromStudent s join s.classes c").list();

for(Iterator iter = students.iterator();iter.hasNext();){

  Object[] obj = (Object[])iter.next();

  System.out.println(obj[0] +", " + obj[1]);

}</span>

5、带参数的查询

(1) ?作为参数 如"from Customer cus where cus.name=?";

     Session session = HibernateSessionFactory.getSession();

    Query query = session.createQuery("fromCustomer cuswhere cus.name=?");

     query.setParameter(0,"zhou");

     List list = query.list();

(2) 参数名称  :name   如" from Customer cus where cus.name=:name";

Sessionsession = HibernateSessionFactory.getSession();

     Queryquery = session.createQuery("fromCustomer cuswhere cus.name=:name");

     query.setParameter("name","zhou");

     List list = query.list();
(3)条件查询,使用 ?的方式传递参数
<p><span style="color:black;"> </span>Query <span style="color:black;">query</span><span style="color:black;"> = </span><span style="color:black;">session.createQuery</span><span style="color:black;">("SELECTs.id, s.name FROM Student s WHERE s.name </span><span style="color:#333399;">LIKE ?</span><span style="color:black;">");</span></p><p><span style="color:black;">  </span> <span style="color:black;">query</span><span style="color:#333399;">.setParameter</span><span style="color:black;">(0,“%</span><span style="color:black;">周</span><span style="color:black;">%”);//</span><span style="color:black;">传递参数参数的索引是从</span><span style="color:black;">0</span><span style="color:black;">开始的。  </span>如条件查询,<span style="color:#333399;">使用</span><span style="color:#333399;">":</span><span style="color:#333399;">参数</span><span style="color:#333399;">"</span><span style="color:#333399;">名称的方式传递参数</span></p><p><span style="color:black;">  </span>Query <span style="color:black;">query</span><span style="color:black;"> = </span><span style="color:black;">session.createQuery</span><span style="color:black;">("SELECTs.id, s.name FROM Student s WHERE s.name </span><span style="color:#333399;">LIKE </span><span style="color:#333399;">:</span><span style="color:#333399;">myname</span><span style="color:black;">");</span></p><p><span style="color:black;">  </span><span style="color:black;">query.setParameter</span><span style="color:black;">("</span><span style="color:black;">myname</span><span style="color:black;">","</span><span style="color:black;">张三</span><span style="color:black;">");//</span><span style="color:black;">传递参数</span></p><p><span style="color:black;">因为</span><span style="color:black;">setParameter</span><span style="color:black;">方法返回</span><span style="color:black;">Query</span><span style="color:black;">接口,所以可用省略方式来查询</span></p><p><span style="color:black;">Liststudents = </span><span style="color:black;">session.createQuery</span><span style="color:black;">("SELECTs.id, s.name FROM Student s WHERE s.name </span><span style="color:#333399;">LIKE :</span><span style="color:#333399;">myname</span><span style="color:#333399;"> and s.id = :</span><span style="color:#333399;">myid</span><span style="color:black;">")</span></p><p><span style="color:black;">setParameter</span><span style="color:black;">("</span><span style="color:black;">myname</span><span style="color:black;">","%</span><span style="color:black;">周</span><span style="color:black;">%").</span><span style="color:black;">setParameter</span><span style="color:black;">("</span><span style="color:black;">myid</span><span style="color:black;">",15).list();</span></p>

6、嵌入原生sql测试

SQLQuerysqlQuery = session.createSQLQuery("select * from t_student");

  List students = sqlQuery.list();

  for (Iterator iter = students.iterator();iter.hasNext();){

  Object[] obj = (Object[])iter.next();

  System.out.println(obj[0] +", " + obj[1]);

  }


2.Hibernate增加、修改方式

拿到要修改的对象,调用session.saveOrUpdate();方法

public void addStudent(Student stud) {
		Session session=HibernateSessionFactory.getSession();
		Transaction tr=session.beginTransaction();
		try {
			session.saveOrUpdate(stud);//一个方法
//			session.update(stud);
		} catch (HibernateException e) {
			e.printStackTrace();
		}
		tr.commit();
}

2.Hibernate删除方式


拿到要删除的对象,调用session.delete();方法

public void delStudent(Student stud) {
		Session session=HibernateSessionFactory.getSession();
		
		Transaction tr=session.beginTransaction();
		try {
			session.delete(stud);
			session.flush();
		} catch (Exception e) {
			System.out.println("回滚了");
//			tr.rollback();
		}
		tr.commit();//删除没有事务不行!
	}


注意要添加事务:不然增删改用不了


二、关于hibernate事务的必须开启的问题

当我们在写简单的增删改的时候,发现如果不开启事务,数据就不会向数据库提交这是因为hibernate中的session对象是Connection对象的子类,对Connection的加强,

而我们在看hibernate源码的时候发现Session对象中通过了代理,自动帮我们把setAtuoCommit(false),设置成不自动提交,所有我们在增删改必须开启事务,而且要提交,同时session还对rollback()进行了代理,所以在commit的时候是自动回滚


三、代码演示

package cn.hncu.demo.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.hncu.domain.Student;
import cn.hncu.hib.HibernateSessionFactory;

public class DemoDaoJdbc {
	public List<Student> queryAllStudent(){
		Session session=HibernateSessionFactory.getSession();
		//无论是Load 还是 Get 都会首先查找缓存(一级缓存) 如果没有,才会去数据库查找,调用Clear() 方法,可以强制清除Session缓存
		session.clear();
		Query query=session.createQuery("from Student");
		List<Student> list=query.list();
		return list;
	}
	public void delStudent(Student stud) {
		Session session=HibernateSessionFactory.getSession();
		
		Transaction tr=session.beginTransaction();
		try {
			session.delete(stud);
			session.flush();
		} catch (Exception e) {
			System.out.println("回滚了");
//			tr.rollback();
		}
		tr.commit();//删除没有事务不行!
	}
	
	@Test
	public void t(){
		Student stud=new Student();
		stud.setStudId("S003");
		delStudent(stud);
		System.out.println(queryAllStudent());
	}

	public void addStudent(Student stud) {
		Session session=HibernateSessionFactory.getSession();
		Transaction tr=session.beginTransaction();
		try {
			session.saveOrUpdate(stud);
//			session.update(stud);
		} catch (HibernateException e) {
			e.printStackTrace();
		}
		tr.commit();
	}

	public Student queryAStudent(Student stud) {
		Session session=HibernateSessionFactory.getSession();
		String hql="from Student s where s.studId=?";
		Query query=session.createQuery(hql);
		query.setParameter(0, stud.getStudId());
		List<Student> list=query.list();
		if(list!=null&&list.size()>0){
			return list.get(0);
		}
		return null;
	}
	public List<Student> queryStudent(Student stud) {
		Session session=HibernateSessionFactory.getSession();
		String hql="from Student s where 1=1";
		if(stud.getStudId()!=null&&stud.getStudId().trim().length()>0){
			hql+=" and s.studId='"+stud.getStudId()+"'";
		}
		if(stud.getStudName()!=null&&stud.getStudName().trim().length()>0){
			hql+=" and s.studName='"+stud.getStudName()+"'";
		}
		if(stud.getStudAge()!=null){
			hql+=" and s.studAge="+stud.getStudAge();
		}
		if(stud.getDeptId()!=null&&stud.getDeptId().trim().length()>0){
			hql+="and s.deptId='"+stud.getDeptId()+"'";
		}
		Query query=session.createQuery(hql);
		List<Student> list=query.list();
		return list;
	}
}

HibernateSessionFactory

package cn.hncu.hib;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {
	private static final String CONFIG_FILENAME="/hibernate.cfg.xml";//文件名
	private static final ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();//本地线程
	private static Configuration config=new Configuration();
	private static SessionFactory sessionFactory;//声明一个SessionFactory对象
	static{
		try {
			config.configure(CONFIG_FILENAME);
			sessionFactory=config.buildSessionFactory();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
	}
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public static Session getSession() throws HibernateException{
		Session session=threadLocal.get();
		if(session==null||!session.isOpen()){//如果这个链接没开
			if (sessionFactory==null) {
				config.configure(CONFIG_FILENAME);
				sessionFactory = config.buildSessionFactory();
			}
			session=(sessionFactory!=null)?sessionFactory.openSession():null;//是否开放一个session
			threadLocal.set(session);//把session放入本地线程
		}
		return session;
	}
	
	//关闭连接
	public static void closeSession() throws HibernateException{
		Session session=threadLocal.get();
		threadLocal.remove();
		if(session!=null){
			session.close();
		}
		
	}

}






  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值