---
title: "【转】hibernate实现有两种配置，xml配置与注释配置"
author: "mib168"
date: "2014-02-07T17:15:31Z"
tags: []
categories: ["企业架构"]
slug: "hibernate-xml"
draft: false
lastmod: "2014-02-07T17:15:30Z"
id: 2009677
url: "https://mib168.iteye.com/blog/2009677"
---

（1）：xml配置：hibernate.cfg.xml （放到src目录下）和实体配置类:xxx.hbm.xml（与实体为同一目录中）

&lt;?xml version='1.0' encoding='utf-8'?&gt;

&lt;!DOCTYPE hibernate-configuration PUBLIC

        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

       "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"&gt;

&lt;hibernate-configuration&gt;

 

    &lt;session-factory&gt;

        &lt;!-- Database connection settings --&gt;

        &lt;property name="connection.driver\_class"&gt;

com.mysql.jdbc.Driver

&lt;/property&gt;

        &lt;property name="connection.url"&gt;

jdbc:mysql://localhost:3306/hxj

&lt;/property&gt;

        &lt;property name="connection.username"&gt;root&lt;/property&gt;

        &lt;property name="connection.password"&gt;root&lt;/property&gt;

 

        &lt;!-- JDBC connection pool (use the built-in) --&gt;

       &lt;property name="connection.pool\_size"&gt;1&lt;/property&gt;

 

        &lt;!-- SQL dialect --&gt;

        &lt;property name="dialect"&gt;

org.hibernate.dialect.MySQLDialect

&lt;/property&gt;

 

        &lt;!-- Enable Hibernate's automatic session context management --&gt;

     &lt;property name="current\_session\_context\_class"&gt;thread&lt;/property&gt;

 

        &lt;!-- Disable the second-level cache --&gt;

        &lt;property name="cache.provider\_class"&gt;

org.hibernate.cache.NoCacheProvider

&lt;/property&gt;

 

        &lt;!-- Echo all executed SQL to stdout --&gt;

        &lt;property name="show\_sql"&gt;true&lt;/property&gt;

 

        &lt;!-- Drop and re-create the database schema on startup --&gt;

       &lt;!—update也可以用create/create-drop/update/validate代替, create 表示可以根据实体配置文件来自动生成表（只能生成表）.

--&gt;

        &lt;property name="hbm2ddl.auto"&gt;update&lt;/property&gt;

 

 // 实体配置类

 &lt;mapping resource="com/wsw/struts/model/Person.hbm.xml"/&gt;

    &lt;/session-factory&gt;

&lt;/hibernate-configuration&gt;

 

(2): **实体配置类：xxx.hbm.xml**

&lt;?xml version="1.0"?&gt;

&lt;!DOCTYPE hibernate-mapping PUBLIC

        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt;

 

&lt;hibernate-mapping package=”com.wsw.struts.model”&gt;

    &lt;class name="Person" table="per"&gt;

       &lt;id name="id" column="id"&gt;

            &lt;generator class="native"/&gt;   //字段自增

       &lt;/id&gt;

       &lt;property name="username" column="p\_username"/&gt;

       &lt;property name="age" column="p\_age"/&gt;

    &lt;/class&gt;

&lt;/hibernate-mapping&gt;

 

（3）：测试类（包括获取SessionFactory类和实体测试类）

SessionFactory类：**HibernateUtil**

**public** **class** HibernateUtil {

    **private** **static** **final** SessionFactory *sessionFactory*;

    **static** {

        **try** {

            // Create the SessionFactory from hibernate.cfg.xml

            *sessionFactory* = **new** Configuration().configure().buildSessionFactory();

        } **catch** (Throwable ex) {

            // Make sure you log the exception, as it might be swallowed

            System.*err*.println("Initial SessionFactory creation failed." + ex);

            **throw** **new** ExceptionInInitializerError(ex);

        }

    }

    **public** **static** SessionFactory getSessionFactory() {

        **return** *sessionFactory*;

    }

}

实体测试类：**PersonManager**

**-----------------------------------------------------------------------------------**

**public** **class** PersonManager {

    **public** **static** **void** main(String\[] args) {

         createAndStorePerson();

        HibernateUtil.*getSessionFactory*().close();

}

 

    **private** **static** **void** createAndStorePerson() {

        Session session =                   // 通过Session工厂获取Session对象

HibernateUtil.*getSessionFactory*().getCurrentSession();

        session.beginTransaction();         //开始事务

       

        Person person = **new** Person();

        person.setUsername("何小景");

        person.setAge(26);

        session.save(person);

       

        session.getTransaction().commit(); // 提交事务

    }

}

 

**（4）：注解方式：**

注解的方式与xml很很多类似：

首先是需要加入4个jar包：hibernate-commons-annotations.jar 、 hibernate-annotations.jar

ejb3-persistence.jar 、 hibernate-jpa-2.0-api-1.0.1.Final.jar

下面是不同的地方：

（1）：hibernate.hbm.xml 文件中把引用：xxx.hbm.xml改为引用实体类：

     即把：&lt;mapping resource="com/wsw/hibernate/model/Person.hbm.xml"/&gt;

改为：&lt;mapping class="com.wsw.hibernate.model.Teacher" /&gt;

（2）：获取SessionFactory方式发生了变化：

      即：由SessionFactory sf = new Configuration().configure().buildSessionFactory()

    改为：SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory()

（3）：注解方式不需要在xxx.hbm.xml把实体类与表进行映射。而采用在实体类中进行注解。

注意：（1）：如果实体类属性名与表字段名不一致的时候，要么都注解在属性前，要么都注解在get方法前。不能部分注解在属性前，部分注解在方法前。

 （2）：如果实体类属性名与表字段名一致的时候，可以部分注解在属性前，部分注解在方法前。

 （3）：如果在实体类中某些属性不注解：（属性和get都不写注解），默认为表字段名与实体类属性名一致。

 （4）：如果实体类的某个成员属性不需要存入数据库中，使用@Transient 进行注解就可以了。即类似于：(xxx.hbm.Xml配置中的某些字段不写(就是不需要对这个成员属性进行映射))

 （5）：表名称可以在实体类前进行注解。

 （6）：所有这些注解在：javax.persistence包下。而不是在hibernate包中。

 ---------------------------------------------------------------------------------------------------------------------

@Entity                        **// 表示为实体类**

@Table(name="t\_teacher")       **// 表名注解**

**public** **class** Teacher **implements** Serializable {

   

    **private** **int** id;

    **private** String username;

    **private** **int** age;

   

    @Id              **// 表示主键**

    @GenericGenerator(name = "generator", strategy = "increment")   @GeneratedValue(generator = "generator")   **// 自增长**

    @Column(name = "id")                                 **// 类属性对应着表字段**

    **public** **int** getId() {

       **return** id;

    }

    **public** **void** setId(**int** id) {

       **this**.id = id;

    }

   

    @Column(name="t\_username")                       **// 类属性对应着表字段**

    **public** String getUsername() {

       **return** username;

    }

   

    **public** **void** setUsername(String username) {

       **this**.username = username;

    }  
    

    @Column(name="t\_age")                      **// 在实体类属性进行注解，类属性对应着表字段**  
    **public** **int** getAge() {

       **return** age;

    }

    **public** **void** setAge(**int** age) {

       **this**.age = age;

    }

转自：[http://www.blogjava.net/yxhxj2006/archive/2012/06/30/381861.html](http://www.blogjava.net/yxhxj2006/archive/2012/06/30/381861.html)