Hibernate: 三种状态和CRUD四种操作

本篇博客是初学hibernate时笔记总结,主要总结hibernate的三种状态和hibernate的CRUD操作。

1. hibernate的三种状态:

  • Transient State : 瞬时状态;
  • Persistent State : 持久状态;
  • Detached State : 离线状态或托管状态;
  • Transient State : 瞬时状态:
    当我们new操作符初始化一个对象时,它处于瞬时态,也就是他没有任何和数据库表相关的行为,只要应用程序不再引用这些对象,它们状态将会丢失,被jvm垃圾回收了。总结,这个对象,Session没管理,数据库中没存。
  • Persistent State : 持久状态 :
    持久化实例则是具有数据库标识的实例,它由持久化管理器Session统一管理的,只要它的状态发生改变,在事务提交时,会同步到数据库中。
  • Detached State : 离线状态或托管状态 : 数据库中有,但是session不管理了,

具体的分析推荐一篇博客写的很详细,也很容易理解,

Hibernate三种状态的详解,

2.CRUD操作;

2.1 Bean对象

package com.qian.domain;

import java.util.Date;

public class User2 { 
    private String user2Id;
    private String user2Name;
    private Date user2CreateDate;

    public String getUser2Id() {
        return user2Id;
    }
    public void setUser2Id(String user2Id) {
        this.user2Id = user2Id;
    }
    public String getUser2Name() {
        return user2Name;
    }
    public void setUser2Name(String user2Name) {
        this.user2Name = user2Name;
    }
    public Date getUser2CreateDate() {
        return user2CreateDate;
    }
    public void setUser2CreateDate(Date user2CreateDate) {
        this.user2CreateDate = user2CreateDate;
    }
}

User2.hbm.xml文件

<?xml version="1.0" encoding="UTF-8"?>

<!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later. ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. -->
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.qian.domain">

    <class name="User2" table="t_User2">
        <id name="user2Id" column="User2_ID">
            <generator class="uuid"/>
        </id>
        <property name="user2Name"/>
        <property name="user2CreateDate"/>

    </class>


</hibernate-mapping>

hibernate.cfg.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later. ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. -->
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:ORCL</property>
        <property name="connection.username">scott</property>
        <property name="connection.password">qian</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>

        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup <property name="hbm2ddl.auto">create</property> -->

        <mapping resource="com/qian/domain/User.hbm.xml"/>
        <mapping resource="com/qian/domain/User2.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

hbm2ddl类

package com.qian.envir;

import java.util.EnumSet;

import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;

/** * http://blog.csdn.net/qinshijangshan/article/details/53314230 * http://bbs.csdn.net/topics/391942178?page=1 * 参考网页来分析所在版本的不同SchemaExport变化的集中方式, * <property name="hbm2ddl.auto">create</property> * @author Administrator * */
public class ExoprotDB {

    public static void main(String[] args) {

        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();

        MetadataImplementor metadataImplementor = (MetadataImplementor) new MetadataSources(serviceRegistry)
                .buildMetadata();

        SchemaExport export = new SchemaExport();

        export.create(EnumSet.of(TargetType.DATABASE), metadataImplementor);

    }

}

HibernateUtil类

package com.qian.envir;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil { 

    private static SessionFactory sessionFactory;

    //生成sessionFactory;
    static{
        final StandardServiceRegistry standardServiceRegistry = new
                StandardServiceRegistryBuilder().configure().build();
        try{
            sessionFactory = new MetadataSources(standardServiceRegistry)
                    .buildMetadata().buildSessionFactory();         
        }catch(Exception e){
            StandardServiceRegistryBuilder.destroy(standardServiceRegistry);
        }
    }

    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }

    public static Session getSession(){
        return sessionFactory.openSession();
    }

    public static void freeSession(Session session){
        if(session!=null){
            if(session.isOpen()){
                session.close();
            }
        }
    }
}

CRUD测试类代码

package test.qian;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.qian.domain.User2;
import com.qian.envir.HibernateUtil;

import junit.framework.TestCase;

public class CRUDTest extends TestCase { 

    public void testCreate(){
        //step one:读取hibernate.cfg.xml文件拿到sessionFactory
        //由于sessionFactory相当于DB的镜像,并且创建很花时间,我们可以写一个工具类只创建一次;
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

        Session session = null;
        Transaction transaction = null;

        try{
        //stpe two: 通过sessionFactroy拿到session
            session = sessionFactory.openSession();
        //step three: 开启事务-->提交是否-->捕获异常事务回滚
            transaction = session.getTransaction();
            transaction.begin();

        //step four: 写添加用户的测试代码
            User2 user2 = new User2();
            user2.setUser2Id("u2id");
            user2.setUser2Name("userName");
            user2.setUser2CreateDate(new Date());

        //step five: 保存到数据库中
            session.save(user2);

            transaction.commit();
        }catch(Exception e){
            transaction.rollback();
            e.printStackTrace();
        }finally{
        //step six: 无论成功与否释放session
            HibernateUtil.freeSession(session);
        }

    }

    public void testReadByGet(){
        //step one:
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session =null;
        Transaction transaction = null;

        try{
            //step two:
            session = sessionFactory.openSession();
            //step three:
            transaction = session.getTransaction();
            transaction.begin();

            //step four:
            //get方法的第一个参数为 Class对象, 第二个参数为Serializable类型(key),也就是根据id查值
            //get方法获取的对象是持久化对象,如果没有找到则返回null,不会报错。
            //发出get查询,它就会马上去数据库中查找,因为是持久化对象,如果我们改变了对象的属性,在最后
            //的commit是,及时没有update,Hibernate也会对照数据库中的对象和内存中的对象,对数据进行更改;

            User2 user2 = session.get(User2.class, "402880da5e50fc2d015e50fc30b10000");
            if(user2!=null)
                System.out.println(user2.getUser2Name()+" : "+user2.getUser2CreateDate());

            //user2.setUser2Name("如果这里对属性操作,会同步到数据库");

            transaction.commit();
        }catch(Exception e){
            transaction.rollback();
            e.printStackTrace();
        }finally{
            HibernateUtil.freeSession(session);
        }
    }

    public void testReadByLoad(){
        //step one:
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session =null;
        Transaction transaction = null;

        try{
            //step two:
            session = sessionFactory.openSession();
            //step three:
            transaction = session.getTransaction();
            transaction.begin();

            //step four:
            //load方法的第一个参数为 Class对象, 第二个参数为Serializable类型(key),也就是根据id查值
            //load方法获取的对象是持久化对象,如果没有找到则抛出对象没找到异常。
            //发出load查询,它不会马上去数据库中查找,而是创建一个User2的代理对象,当真正用的时候才会
            //向数据库发出查询语句。也就是load使用CGLIB的动态代理来实现懒加载的。
            //的commit是,及时没有update,Hibernate也会对照数据库中的对象和内存中的对象,对数据进行更改;

            User2 user2 = session.load(User2.class, "402880da5e50fc2d015e50fc30b10000");

            System.out.println(user2.getUser2Name()+" : "+user2.getUser2CreateDate());

            user2.setUser2Name("如果持久化对象 对属性操作,会同步到数据库");

            transaction.commit();
        }catch(Exception e){
            transaction.rollback();
            e.printStackTrace();
        }finally{
            HibernateUtil.freeSession(session);
        }
    }

    public void testUpdate(){
        //step one:
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session =null;
        Transaction transaction = null;

        try{
        //step two:
            session = sessionFactory.openSession();
        //step three:
            transaction = session.getTransaction();
            transaction.begin();

        //step four:
            User2 user2 = session.load(User2.class, "402880da5e50fc2d015e50fc30b10000");
            user2.setUser2Name("zhangSan");
        //step five:
            session.update(user2);

            transaction.commit();
        }catch(Exception e){
            transaction.rollback();
            e.printStackTrace();
        }finally{
            HibernateUtil.freeSession(session);
        }
    }

    public void testDelete(){
        //step one:
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session =null;
        Transaction transaction = null;

        try{
            //step two:
            session = sessionFactory.openSession();
            //step three:
            transaction = session.getTransaction();
            transaction.begin();

            //step four:
            User2 user2 = session.load(User2.class, "402880da5e50fc2d015e50fc30b10000");
            session.delete(user2);
            System.out.println("delete successfully");

            transaction.commit();
        }catch(Exception e){
            transaction.rollback();
            e.printStackTrace();
        }finally{
            HibernateUtil.freeSession(session);
        }
    }
}
    原文作者:Coder-Qian
    原文地址: https://blog.csdn.net/ManagementAndJava/article/details/77854743
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞