hibernate 基本的CRUD增删改查方法

来源:互联网 发布:长沙网络自考 编辑:程序博客网 时间:2024/05/22 01:48
hibernate核心api 有6大类
Session SessionFactory Transcation Query Criteria Configuration
1.Session接口负责执行被持久化对象的CRUD操作,非线程安全的
2.SessionFactory接口负责初始化Hibernate。它充当数据存储源的代理,并负责创建Session对象。
3.TransactionTransaction 接口是一个可选的API,处理事务的
4.Query接口让你方便地对数据库及持久对象进行查询,它可以有两种表达方式:HQL语言或本地数据库的SQL语句。
5.Criteria接口与Query接口非常类似,允许创建并执行面向对象的标准化查询。
6.Configuration 类的作用是对Hibernate 进行配置,以及对它进行启动。它是启动hibernate 时所遇到的第一个对象。
用他创建一个SessionFactory对象。
=====================================================


Hibernate 中提供了两级Cache(高速缓冲存储器),
第一级别的缓存是Session级别的缓存,其实就是一个map对象,在内存中,一般不用管理,事务级的缓存
第二级别的缓存是SessionFactory级别的缓存,在内存和硬盘中,可以配置和更改可以动态加载和卸载。进程级的缓存


=====================================================
hibernate的3种状态


瞬时transient
持久persistent
游离datached


这三种状态就是对象在session和数据库中的存在关系,属于一级缓存范围
瞬时状态就是刚new出来一个对象,还没有被保存到数据库中,即数据库中没有session中也没有。
持久化状态就是已经被保存到数据库中,并在Session中,即数据库中有session中也有
离线状态就是数据库中有,但是session中不存在该对象


瞬时状态(临时状态):
new 出来的对象   
delete()


持久状态:
对象被 save()   get() load() find() iterator()
update() saveOrUpdate()  merger() lock()


游离状态:

evict()  close() clear()


代码演示==================================================

Student实体类

package cn.hibernate.entity;import java.io.Serializable;/** * Student实体类 * @author Administrator * */public class Student implements Serializable{private static final long serialVersionUID = 1234L;private int id; // OIDprivate String name; //姓名private String clazz; //科目private int score; //分数public Student(int id, String name, String clazz, int score) {super();this.id = id;this.name = name;this.clazz = clazz;this.score = score;}public Student( String name, String clazz, int score) {super();this.name = name;this.clazz = clazz;this.score = score;}public Student() {super();}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getClazz() {return clazz;}public void setClazz(String clazz) {this.clazz = clazz;}public int getScore() {return score;}public void setScore(int score) {this.score = score;}}

dao层 数据访问层

package cn.hibernate.dao;import java.io.Serializable;import org.hibernate.Session;import cn.hibernate.common.HibernateSessionFactory;import cn.hibernate.entity.Student;/** * 数据访问层 * @author Administrator * */public class StudentDao {//新增public void add(Student stu){try {HibernateSessionFactory.getSession().save(stu);} catch (Exception e) {//System.out.println("新增失败"+e);throw new RuntimeException("新增失败",e);}}//修改public void update(Student stu){try {HibernateSessionFactory.getSession().update(stu);} catch (Exception e) {throw new RuntimeException("修改失败",e);}}//新增or修改public void saveOrUpdate(Student stu){try {HibernateSessionFactory.getSession().merge(stu);} catch (Exception e) {throw new RuntimeException("修改失败",e);}}//根据id 返回student对象public Student get(Serializable id){return HibernateSessionFactory.getSession().get(Student.class,id);}public Student load(Serializable id){return HibernateSessionFactory.getSession().load(Student.class,id);}public Student find(Serializable id){return HibernateSessionFactory.getSession().find(Student.class,id);}public void delect(Student stu){HibernateSessionFactory.getSession().delete(stu);}public void close(){HibernateSessionFactory.getSession().clear();}public void evict(Student stu){HibernateSessionFactory.getSession().evict(stu);}}

biz层 业务处理层

package cn.hibernate.biz;import java.io.Serializable;import org.hibernate.Session;import org.hibernate.Transaction;import cn.hibernate.common.HibernateSessionFactory;import cn.hibernate.dao.StudentDao;import cn.hibernate.entity.Student;//业务处理层public class StudentBiz {private StudentDao dao = new StudentDao();public void evict(Student stu){Transaction tx = null;try {tx = HibernateSessionFactory.getSession().beginTransaction();dao.evict(stu);tx.commit();} catch (Exception e) {if(tx!=null){tx.rollback();//回滚事务}}}public void delete(Student stu){Transaction tx = null;try {tx = HibernateSessionFactory.getSession().beginTransaction();dao.delect(stu);tx.commit();} catch (Exception e) {if(tx!=null){tx.rollback();//回滚事务}}}public Student getStu(Serializable id){Transaction tx = null;Student stu = null;try {tx = HibernateSessionFactory.getSession().beginTransaction();stu = dao.find(id);dao.close();stu.setClazz("php");tx.commit();} catch (Exception e) {if(tx!=null){tx.rollback();//回滚事务}}return stu;}public void saveOrUpdate(Student stu){Transaction tx = null;try {tx = HibernateSessionFactory.getSession().beginTransaction();dao.saveOrUpdate(stu);stu.setName("meger111");tx.commit();} catch (Exception e) {if(tx!=null){tx.rollback();//回滚事务}}}public void update(Student stu){Transaction tx = null;try {tx = HibernateSessionFactory.getSession().beginTransaction();dao.update(stu);tx.commit();} catch (Exception e) {if(tx!=null){tx.rollback();//回滚事务}}}public void addStu(Student stu){Transaction tx = null;try {tx = HibernateSessionFactory.getSession().beginTransaction();dao.add(stu);/** * 此时stu是持久化状态,已经被session所管理,当在提交时,会把session中的对象和目前的对象进行比较 * 如果两个对象中的值不一致就会继续发出相应的sql语句 */tx.commit();System.out.println("新增成功");} catch (Exception e) {if(tx!=null){tx.rollback();//回滚事务}}}}

读取配置文件类

package cn.hibernate.common;import java.util.Iterator;import java.util.Map;import java.util.Properties;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;/** * 读取配置文件的类 * @author Administrator * */public class HibernateSessionFactory {private static Configuration cfg; //读取配置文件private static SessionFactory sessionfactory;//链接数据库的会话工厂 只创建一次static {try {cfg  = new Configuration().configure();//Properties props = cfg.getProperties();//props.list(System.out);sessionfactory = cfg.buildSessionFactory();//Map<String, Object> properties = sessionfactory.getProperties();//for(Map.Entry<String,Object> entry : properties.entrySet()){//System.out.println(entry.getKey()+";;;"+entry.getValue());////}//System.out.println(sessionfactory);} catch (HibernateException e) {throw new RuntimeException("初始化失败",e);}}//创建session时和线程绑定,每个用户得到是唯一的session  需要事务才可以操作public static Session getSession(){Session currentSession = null;try {currentSession = sessionfactory.getCurrentSession();//System.out.println("session:"+currentSession);} catch (HibernateException e) {//System.out.println("创建session 失败!"+e);throw new RuntimeException("创建session 失败!",e);}return currentSession;}}
test测试类

package cn.hibernate.test;import cn.hibernate.biz.StudentBiz;import cn.hibernate.entity.Student;public class Test {public static void main(String[] args) {Student stu = new Student();stu.setId(2);StudentBiz biz = new StudentBiz();biz.evict(stu);}}

方法比较

get() 和load()方法

这两个方法都可以获取类实例对象,但是get()方法是直接从数据库获取,load()先从session一级缓存(内存)中查找再到二级缓存中查找最后才到数据库

get()方法不受配置文件是否懒加载约束,load()方法查找需要结合配置文件是否为懒加载查找,由于默认情况下映射配置文件为懒加载模式,即lazy='"true",

所以当事务提交后session就结束了,后续如果对实体对象进行其他操作都不会更新到数据库里,而且获取到的实体对象如果没有保存获取对象操作,则最后关闭session后想要获取对象就会报session 为null .

修改建议在映射配置文件中class 类添加参数 lazy = "false" 但是这种方法的弊端就是执行效率低

第二种修改可以用OpenSessionInViewFilter 在web.xml中进行配置,同一管理session的开启和关闭 当有请求发出时 session开启,当响应结束 session结束

============================================================================================================

merger()和saveOrUpdate()方法比较

当调用merger()方法时,如果实体类没有id 则会调用save()方法,利用hibernate配置文件中id创建规则创建类对象,如果有id且数据库存在该id,则update()更新数据和saveOrUpdate()方法一致。但是merger()方法对实体类不会变为持久态persistent,但是可以操作持久态数据,而saveOrUpdate()可以将游离态数据变为持久态。且saveOrUpdate方法必须指明主键id

该对象需要是游离态对象才可以调用 转成持久态。


close()方法为关闭session,事务,可以将持久态变为游离态对象,当调用该方法后 提交事务就会报错

clear() 清除方法,可以将持久态变为游离态对象


原创粉丝点击