浅谈hibernate

a、应用程序先调用Configuration类,该类读取Hibernate配置文件及映射文件中的信息,

b、并用这些信息生成一个SessionFactory对象,

c、然后从SessionFactory对象生成一个Session对象,

d、并用Session对象生成Transaction对象,开启事务;

e、可通过Session对象的get(),load(),save(),update(),delete()和saveOrUpdate()、createQuery()等方法对进行CURD等操作;

f、提交事物

g、关闭资源

下面对各部分进行详解

1、hibernate.cfg.xml配置文件

作用:a、配置连接资库的信息

b、配置hibernate自身拥有的一些属性

如:

#使用的哪一种数据库

<prop key="hibernate.dialect">com.bsoft.bschis.dialect.MyOracle10gDialect</prop>

#是否开启展示的sql
<prop key="hibernate.show_sql">true</prop>

#开启二级缓存
<prop key="hibernate.generate_statistics">true</prop>

#连接的释放模式
<prop key="hibernate.connection.release_mode">auto</prop>

#
<prop key="hibernate.autoReconnect">true</prop>

#设定JDBC的Statement读取数据的时候每次从数据库中取出的记录条数
<prop key="hibernate.jdbc.fetch_size">100</prop>

#Fetch Size 是设定JDBC的Statement读取数据的时候每次从数据库中取出的记录条数
<prop key="hibernate.jdbc.batch_size">50</prop>

c、配置映射文件

2、映射文件

<hibernate-mapping>

<class entity-name="java实体类" table="表名">
<id name="主键" type="主键类型">
<column name="主键" />
<generator class="自增策略" />
</id>

<property name="类属性" colm="表字段" type="表类型" length="长度" />

</hibernate-mapping>

3、对hibernate 的使用

 @Before
    public void before(){
        //创建配置对象
        Configuration config = new Configuration().configure();
        //创建服务注册对象
        ServiceRegistry service = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //创建会话工厂对象
        sessionFactory = config.buildSessionFactory(service);
        //创建会话对象
        session = sessionFactory.openSession();
        //开启事务
        transaction = session.beginTransaction();
    }

    @After
    public void after(){
        transaction.commit();    //提交事务
        session.close();        //关闭会话
        sessionFactory.close(); //关闭会话工厂
    }
    
    @Test
    public void testSaveStudent() {
        //创建学生对象
        Student s = new Student(1,"张三","男",new Date(),"武当山");
        /*
         * 由于hibernate.cfg.xml中配置的hbm2ddl.auto值为'Create',所以执行save
         * 方法会检查数据库中是否有student表,没有的话会创建此表,并将s对象保存进去
         */
        session.save(s);
    }
原文地址:https://www.cnblogs.com/zj-xu/p/10861358.html