Hibernate實現有兩種配置,xml配置與註釋配置

hibernate實現有兩種配置,xml配置與註釋配置。java

(1):xml配置:hibernate.cfg.xml (放到src目錄下)和實體配置類:xxx.hbm.xml(與實體爲同一目錄中)mysql

<?xml version='1.0' encoding='utf-8'?>sql

<!DOCTYPE hibernate-configuration PUBLIC數據庫

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

       "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">session

<hibernate-configuration>app

 

    <session-factory>ide

        <!-- Database connection settings -->測試

        <property name="connection.driver_class">ui

com.mysql.jdbc.Driver

</property>

        <property name="connection.url">

jdbc:mysql://localhost:3306/hxj

</property>

        <property name="connection.username">root</property>

        <property name="connection.password">root</property>

 

        <!-- JDBC connection pool (use the built-in) -->

       <property name="connection.pool_size">1</property>

 

        <!-- SQL dialect -->

        <property name="dialect">

org.hibernate.dialect.MySQLDialect

</property>

 

        <!-- Enable Hibernate's automatic session context management -->

     <property name="current_session_context_class">thread</property>

 

        <!-- Disable the second-level cache -->

        <property name="cache.provider_class">

org.hibernate.cache.NoCacheProvider

</property>

 

        <!-- Echo all executed SQL to stdout -->

        <property name="show_sql">true</property>

 

        <!-- Drop and re-create the database schema on startup -->

       <!—update也能夠用create/create-drop/update/validate代替, create 表示能夠根據實體配置文件來自動生成表(只能生成表).

-->

        <property name="hbm2ddl.auto">update</property>

 

 // 實體配置類

 <mapping resource="com/wsw/struts/model/Person.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

 

(2): 實體配置類:xxx.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

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

        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

 

<hibernate-mapping package=」com.wsw.struts.model>

    <class name="Person" table="per">

       <id name="id" column="id">

            <generator class="native"/>   //字段自增

       </id>

       <property name="username" column="p_username"/>

       <property name="age" column="p_age"/>

    </class>

</hibernate-mapping>

 

(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改成引用實體類:

     即把:<mapping resource="com/wsw/hibernate/model/Person.hbm.xml"/>

改成:<mapping class="com.wsw.hibernate.model.Teacher" />

(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;

相關文章
相關標籤/搜索