Hibernate之全面认识

Hibernate体系架构

Hibernate通过配置文件管理底层的JDBC连接,将用户从原始的JDBC释放出来,使得用户无需再关注底层的JDBC操作,而是以面向对象的方式进行持久化操作。这种全面的解决方案架构如下(插图来自官方文档 manual:Comprehensive architecture)

image

大致解释一下上面的关键分层模块:
- ==SessionFactory==: 是==单个数据库映射关==系经过编译后的内存镜像,是==线程安全==的。该对象可在进程或者集群的级别上,为事务直接可重用数据提供二级缓存。
- ==Session==:是应用程序与持久层交互的一个==单线程==的对象,==所有持久化的对象都必须在Session管理下才可以进行持久化操作==。Session封装了JDBC,也是Transaction工厂。
- 持久化对象:是一个与Session关联的普通对象(POJO).
- 瞬态和脱管:未与Sessio==n关联的POJO处于==瞬态==。如果关联之后,Session如果关闭了,则此POJO转为==脱管状态。
- ConnectionProvider:是生成JDBC连接的工厂。将应用程序与底层的DataSource及DriverManager隔离开。应用程序一般无需直接访问这个对象。
- TransactionFactory:生成Transaction对象的工厂。应用程序一般无需直接访问这个对象。

Hibernate的配置文件

Hibernate持久化操作离不开SessionFactory对象,而SessionFactory对象是由Configuration对象创建的(build)。每一个Hibernate配置文件对应一个Configuration对象,创建Configuration对象的方式有三种:

1.使用hibernate.properties配置文件——这种方式不能在配置文件中直接添加映射文件,而是需要写到java code里面,所以比较麻烦:

在Hibernate发布包的\project\etc下有一个hibernate.properties的用例,比较全面,部分配置如下,

## HypersonicSQL

hibernate.dialect org.hibernate.dialect.HSQLDialect
hibernate.connection.driver_class org.hsqldb.jdbcDriver
hibernate.connection.username sa
hibernate.connection.password
hibernate.connection.url jdbc:hsqldb:./build/db/hsqldb/hibernate
#hibernate.connection.url jdbc:hsqldb:hsql://localhost
#hibernate.connection.url jdbc:hsqldb:test
....

有了这个配置文件还不够,还需要在java code中写明映射文件名称,通过addResource(“xxx.xml”)方式可以添加映射文件,

Configuration cfg = new Configuration()
 .addResource("a.hbm.xml")
 .addResource("b.hbm.xml");

另外,也可以通过addClass(“xxx.class”)的方式直接添加实体类的Class实例,hibernate会自动搜索对应的映射文件,但是要求将映射文件和实体类放在同一个目录下。

这种方式有个好处就是消除了系统对文件名的硬编码耦合。

Configuration cfg = new Configuration()
 .addClass(hib.a.class)
 .addClass(hib.b.class);

2.使用hibernate.cfg.xml配置文件

即前面的例子,在hibernate.cfg.xml中配置hibernate连接信息,数据池等信息,另外还需要将映射文件名也添加进去,配置如下,

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  

<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=UTF-8</property> <!-- 指定字符集的方式-->
        <property name="connection.username">root</property>
        <property name="connection.password"></property> 

        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.min_size">1</property>

        <property name="hibernate.c3p0.timeout">5000</property>

        <property name="hibernate.c3p0.max_statements">100</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
        <property name="hibernate.c3p0.acquire_increment">2</property>
        <property name="hibernate.c3p0.validate">true</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 

        <property name="hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>
        <mapping resource="hib/News.hbm.xml" />
    </session-factory>
</hibernate-configuration>

配置文件中,需要注意以下几项配置:

1).编码:可以在url中指定,例如在hibernate.property中,setProperty(“hibernate.connection.url”,”jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8”)

在hibernate.cfg.xml中, jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8 ,注意在xml文件中&符号要用 &转义.

2).数据库方言hibernate.dialect,可以在官方手册中查找对应的选项
3).自动建表 hibernate.hbm2ddl.auto有三种取值,update, create, create-drop
4).hibernate.show_sql和hibernate.format_sql有助于调试sql,前者可以打印sql到控制台,后者进行格式化

映射文件News.hbm.xml

<?xml version="1.0"  encoding="UTF-8"?>    
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  

<hibernate-mapping package="hib">
    <class name="News" table="news_table">
        <id name="id" column="id" type="int">
            <generator class="identity" />
        </id>
        <property name="title" type="string" column="title" />
        <property name="content" type="string" column="content" />
    </class>
</hibernate-mapping>

3.不使用任何配置文件,所有配置都以编码方式(.setProperty(key,value))来创建Configuration对象

public static void noConfigFile() {
    Configuration cfg = new Configuration()
            .addClass(hib.News.class)
            .setProperty("hibernate.connection.driver_class","com.mysql.jdbc.Driver")
            .setProperty("hibernate.connection.url","jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8")
            .setProperty("hibernate.connection.username", "root")
            .setProperty("hibernate.connection.password", "")
            .setProperty("hibernate.c3p0.max_size", "20")
            .setProperty("hibernate.c3p0.min_size", "1")
            .setProperty("hibernate.c3p0.max_statements", "100")
            .setProperty("hibernate.c3p0.timeout", "5000")
            .setProperty("hibernate.c3p0.idle_test_period", "3000")
            .setProperty("hibernate.c3p0.acquire_increment", "2")
            .setProperty("hibernate.validate", "true")
            .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
            .setProperty("hibernate.hbm2dll.auto", "create")
            .setProperty("hibernate.show_sql", "true");
    SessionFactory sf = cfg.buildSessionFactory();
    Session sess = sf.openSession();
    Transaction tx = sess.beginTransaction();
    News n = new News();
    n.setTitle("举头望明月");
    n.setContent("低头思故乡");
    sess.save(n);
    tx.commit();
    sess.close();
}

猜你喜欢

转载自blog.csdn.net/ice_cream__/article/details/78683404