Hibernate(二) 数据库的操作 增删查改

一,Hibernate API

Configuration
SessionFactory
Session

Transaction

Query

二,知识点

1.读取并解析配置文件及映射文件

Configuration conf=new Configuration().configure(); 

2.依据配置文件和映射文件的信息,创建SessionFactory

SessionFactory sf=conf.buildSessionFactory();

3.打开Session 有2种方法

1)session=sf.openSession();         //结束时  需要关闭session 资源    session.close();

2)session=sf.getCurrentSession();  //结束时,不需要关闭session 资源

4.事务

  tx=session.beginTransaction();   //开始一个事务

  tx.commit();                               //提交事务

  tx.rollback();                              //事务回滚

5.主键生成策略

mysql或sqlserver数据库自动增长:主键 identity,数据库自动增长;主键 assigned ,添加记录时,需要自己添加ID。

6.数据库操作

查询:

    session.get(实体类名.class, id);     //如果数据库没有 对应ID的记录 ,返回null

    session.load(实体类名.class, id);   //如果数据库没有 对应ID的记录 ,报错

添加:session.save(实体类);

删除:session.delete(实体类);

修改:session.update(实体类);


三,数据库操作

  • 几个Demo

1.添加   

创建 一个dao类 DeptAddTest.java ,代码如下:

package cn.hibernatedemo.dao;

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

import cn.hibernatedemo.entity.Dept;

public class DeptAddTest {
    public static void main(String[] args) {
    	Configuration conf=null;
    	SessionFactory sf=null;
    	Session session=null;                 
    	Transaction tx=null;  //事务
    	try{
    		//1.读取并解析配置文件及映射文件
     		conf=new Configuration().configure(); 
        	//2.依据配置文件和映射文件的信息,创建SessionFactory
    		sf=conf.buildSessionFactory();
        	//3.打开Session
    		//     打开有2种方法
            //     1.openSession(),需要关闭
   	        /* session=sf.openSession();*/
   	         //    2.getCurrentSession(),不需要关闭
   	         session=sf.getCurrentSession();
        	//4.开始一个事务
   	         tx=session.beginTransaction();
        	//5.数据库的操作
   	         Dept dept=new Dept();
   	         dept.setDeptNo(null);  //mysql或sqlserver数据库自动增长,主键 identity,数据库自动增长,主键 assigned
   	         dept.setDeptName("开发部");
   	         dept.setLocation("西青区");
   	         session.save(dept);
        	//6.提交事务
   	         tx.commit();
        	//7.关闭资源   SessionFactory可以不用关闭  ;Session每个事务都要打开 ,需要关闭。
   	     //    session.close();
    	}catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
}

2.查询

1)session.get()方法获得

创建一个dao类 DeptQueryByKeyGetTest.java,代码如下;

package cn.hibernatedemo.dao;

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

import cn.hibernatedemo.entity.Dept;

public class DeptQueryByKeyGetTest {
	 public static void main(String[] args) {
	    	Configuration conf=null;
	    	SessionFactory sf=null;
	    	Session session=null;                 
	    	Transaction tx=null;  //事务
	    	try{
	    		//1.读取并解析配置文件及映射文件
	    		conf=new Configuration().configure(); 
	        	//2.依据配置文件和映射文件的信息,创建SessionFactory
	    		sf=conf.buildSessionFactory();
	        	//3.打开Session
	    		//     打开有2种方法
	            //     1.openSession(),需要关闭
	   	        /* session=sf.openSession();*/
	   	         //    2.getCurrentSession(),不需要关闭
	   	         session=sf.getCurrentSession();
	        	//4.开始一个事务
	   	         tx=session.beginTransaction();
	        	//5.数据库的操作
	   	         Dept dept=new Dept();
	   	         dept=(Dept)session.get(Dept.class, 1);            
	        	//6.提交事务
	   	         tx.commit();
	        	//7.关闭资源   SessionFactory可以不用关闭  ;Session每个事务都要打开 ,需要关闭。
	   	       //  session.close();
	    	}catch (HibernateException e) {
				e.printStackTrace();
				tx.rollback();
			}
		}
}

2)session.load()方法获得

创建一个dao类 DeptQueryByLoadGetTest.java ,代码如下:

package cn.hibernatedemo.dao;

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

import cn.hibernatedemo.entity.Dept;

public class DeptQueryByLoadGetTest {
	 public static void main(String[] args) {
	    	Configuration conf=null;
	    	SessionFactory sf=null;
	    	Session session=null;                 
	    	Transaction tx=null;  //事务
	    	try{
	    		//1.读取并解析配置文件及映射文件
	    		conf=new Configuration().configure(); 
             
	        	//2.依据配置文件和映射文件的信息,创建SessionFactory
	    		sf=conf.buildSessionFactory();
	        	//3.打开Session
	    		//     打开有2种方法
	            //     1.openSession(),需要关闭
	   	        /* session=sf.openSession();*/
	   	         //    2.getCurrentSession(),不需要关闭
	   	         session=sf.getCurrentSession();
	        	//4.开始一个事务
	   	         tx=session.beginTransaction();
	        	//5.数据库的操作
	   	         Dept dept=new Dept();
	   	      //  dept=(Dept)session.get(Dept.class, 13);        //不存在  返回null
	   	         dept=(Dept)session.load(Dept.class, 1);        //不存在   报错
	   	         System.out.println("Dept="+dept.toString());
	        	//6.提交事务
	   	         tx.commit();
	        	//7.关闭资源   SessionFactory可以不用关闭  ;Session每个事务都要打开 ,需要关闭。
	   	     //    session.close();
	    	}catch (HibernateException e) {
				e.printStackTrace();
				tx.rollback();
			}
		}
}

3.更新

创建一个dao类,代码如下:

package cn.hibernatedemo.dao;

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

import cn.hibernatedemo.entity.Dept;

public class DeptUpdateTest {
    public static void main(String[] args) {
    	Configuration conf=null;
    	SessionFactory sf=null;
    	Session session=null;                 
    	Transaction tx=null;  //事务
    	try{
    		//1.读取并解析配置文件及映射文件
     		conf=new Configuration().configure(); 
        	//2.依据配置文件和映射文件的信息,创建SessionFactory
    		sf=conf.buildSessionFactory();
        	//3.打开Session
    		//     打开有2种方法
            //     1.openSession(),需要关闭
   	        /* session=sf.openSession();*/
   	         //    2.getCurrentSession(),不需要关闭
   	         session=sf.getCurrentSession();
        	//4.开始一个事务
   	         tx=session.beginTransaction();
        	//5.数据库的操作
   	         Dept dept=new Dept();
   	         dept=(Dept)session.get(Dept.class, 1);
   	         dept.setDeptName("aha");
   	         dept.setLocation("nicai");
        	//6.提交事务
   	         tx.commit();
        	//7.关闭资源   SessionFactory可以不用关闭  ;Session每个事务都要打开 ,需要关闭。
   	     //    session.close();
    	}catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
}

4.删除

创建一个dao类,DeptDeleteTest.java ,代码如下:

package cn.hibernatedemo.dao;

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

import cn.hibernatedemo.entity.Dept;

public class DeptDeleteTest {
    public static void main(String[] args) {
    	Configuration conf=null;
    	SessionFactory sf=null;
    	Session session=null;                 
    	Transaction tx=null;  //事务
    	try{
    		//1.读取并解析配置文件及映射文件
     		conf=new Configuration().configure(); 
        	//2.依据配置文件和映射文件的信息,创建SessionFactory
    		sf=conf.buildSessionFactory();
        	//3.打开Session
    		//     打开有2种方法
            //     1.openSession(),需要关闭
   	        /* session=sf.openSession();*/
   	         //    2.getCurrentSession(),不需要关闭
   	         session=sf.getCurrentSession();
        	//4.开始一个事务
   	         tx=session.beginTransaction();
        	//5.数据库的操作
   	         Dept dept=new Dept();
   	         dept=(Dept)session.get(Dept.class, 1);
   	         session.delete(dept);
        	//6.提交事务
   	         tx.commit();
        	//7.关闭资源   SessionFactory可以不用关闭  ;Session每个事务都要打开 ,需要关闭。
   	     //    session.close();
    	}catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
}
  • 统一封装

1. 创建一个 读取 配置文件, 获得Session 的 工具类 HibernateUtil.java ,代码如下:

package cn.hibernatedemo.dao;

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

/**
 * 
 * @author LiuZJ
 * 
 */
public class HibernateUtil {
	// static 唯一性
	// final 不被继承
	private static Configuration configuration;
	private static final SessionFactory sessionFactory;
	// 初始化 Configuration 和 SessionFactory
	static {
		try{
		// 1.读取并解析配置文件及映射文件
		configuration = new Configuration().configure();
		// 2.依据配置文件和映射文件的信息,创建SessionFactory
		sessionFactory = configuration.buildSessionFactory();
		}catch (HibernateException e) {
			// TODO: handle exception
			throw new ExceptionInInitializerError(e);
		}
	}
	public HibernateUtil(){
		
	}
	//获取Session对象
	public static Session currentSession(){
		return sessionFactory.getCurrentSession();
	}
		

}

2. 可以创建一个 BaseDao.java   ,获得Session代码如下:

package cn.hibernatedemo.dao;

import org.hibernate.Session;

public class BaseDao {
	public Session currentSession() {
		return HibernateUtil.currentSession();
	}
}

3. 创建一个 DeptDao.java  继承BaseDao 代码如下

package cn.hibernatedemo.dao;

import cn.hibernatedemo.entity.Dept;

public class DeptDao extends BaseDao{
	//通过Session 的get()方法,根据OID 加载指定对象
	public Dept get(int id){
		return (Dept) currentSession().get(Dept.class, id);
	}
    //通过Session 的load()方法,根据OID 加载指定对象
	public Dept load(int id){
		return (Dept) currentSession().load(Dept.class, id);
	}
	//保存指定的Dept对象
	public void save(Dept dept){
		  currentSession().save(dept);
	}
	//修改指定的Dept对象
	public void update(Dept dept){
		 currentSession().update(dept);
	}
	//删除指定的Dept对象
	public void delete(Dept dept){
		 currentSession().delete(dept);
	}
}

4.创建一个Service 层  

创建一个 service类 DeptBiz.java ,代码如下:

package cn.hibernatedemo.service;

import org.hibernate.HibernateException;
import org.hibernate.Transaction;

import cn.hibernatedemo.dao.DeptDao;
import cn.hibernatedemo.dao.HibernateUtil;
import cn.hibernatedemo.entity.Dept;

public class DeptBiz {
	private DeptDao dao = new DeptDao();

	public DeptDao getDao() {
		return dao;
	}

	public void setDao(DeptDao dao) {
		this.dao = dao;
	}

	// 通过DeptDao.get()方法加载数据
	public Dept findDeptById(int id) {
		Transaction tx = null; // 事务
		Dept result = null;
		try {
			tx = HibernateUtil.currentSession().beginTransaction();
			result = dao.get(id);
			tx.commit();
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			if (tx != null) {
				tx.rollback();
			}
		}
		return result;
	}

	// 通过DeptDao.load()方法加载数据
	public Dept findDeptById2(int id) {
		Transaction tx = null; // 事务
		Dept result = null;
		try {
			tx = HibernateUtil.currentSession().beginTransaction();
			result = dao.load(id);
			tx.commit();
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			if (tx != null) {
				tx.rollback();
			}
		}
		return result;
	}

	// 添加一个Dept
	public void addNewDept(Dept dept) {
		Transaction tx = null; // 事务
		try {
			tx = HibernateUtil.currentSession().beginTransaction();
			dao.save(dept);
			tx.commit();
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			if (tx != null) {
				tx.rollback();
			}
		}
	}

	// 修改一个Dept
	public void updateDept(Dept dept) {
		Transaction tx = null; // 事务
		try {
			tx = HibernateUtil.currentSession().beginTransaction();
			dao.update(dept);
			tx.commit();
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			if (tx != null) {
				tx.rollback();
			}
		}
	}

	// 删除一个Dept
	public void deleteDept(int id) {
		Transaction tx = null; // 事务
		try {
			tx = HibernateUtil.currentSession().beginTransaction();
			Dept dept=dao.get(id);
			dao.delete(dept);
			tx.commit();
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			if (tx != null) {
				tx.rollback();
			}
		}
	}
}

5.创建一个测试类  DeptTest.java,测试一下  

package cn.hibernatedemo.test;

import cn.hibernatedemo.entity.Dept;
import cn.hibernatedemo.service.DeptBiz;

public class DeptTest {
		
		public static void main(String[] args) {
			DeptBiz deptBiz=new DeptBiz();
			//----查询
	/*		Dept dept=deptBiz.findDeptById(1);
			System.out.println("dept="+dept.toString());*/
			//----添加
	/*		deptBiz.addNewDept(new Dept("nicai","a"));*/
			//----修改
	/*		Dept dept2=new Dept(1,"叫", "爸爸");
			deptBiz.updateDept(dept2);*/
			//----删除
		/*	deptBiz.deleteDept(5);*/
		}
}







猜你喜欢

转载自blog.csdn.net/lzj470612639/article/details/79634564