yxhxj2006

          常用鏈接

          統計

          最新評論

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

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

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

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

          <!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">

          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很很多類似:

          首先是需要加入4jar包: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;

              }

             

          posted on 2012-06-30 10:00 奮斗成就男人 閱讀(49848) 評論(4)  編輯  收藏

          評論

          # re: Hibernate實現有兩種配置,xml配置與注釋配置 2014-05-20 16:35 胡淘

          我想把entity單獨抽出來作為一個公共的模塊,或者說一個單獨的項目,反正和dao這一層分開。那是不是只能用配置文件注解了?  回復  更多評論   

          # re: Hibernate實現有兩種配置,xml配置與注釋配置 2014-08-20 18:01 楊宇

          在一個文件夾下就行好比說你的實體類文件夾是 entity 你只要把所有的類名.hbm.xml都放在這個entity文件夾下就行@胡淘
            回復  更多評論   

          # re: Hibernate實現有兩種配置,xml配置與注釋配置 2015-12-19 16:27 小涂

          這是hibernate的那個版本(4.3能用嗎)  回復  更多評論   

          # re: Hibernate實現有兩種配置,xml配置與注釋配置[未登錄] 2016-04-15 15:22 sa

          sa  回復  更多評論   


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 溆浦县| 枣庄市| 扎囊县| 乐昌市| 南丰县| 客服| 齐河县| 隆林| 依安县| 南部县| 静海县| 阳城县| 曲阜市| 简阳市| 石门县| 聂拉木县| 陆良县| 陕西省| 永胜县| 从化市| 嘉禾县| 建阳市| 上杭县| 连山| 岳池县| 南安市| 雅安市| 建昌县| 贵州省| 开平市| 景泰县| 南阳市| 科技| 福建省| 凌云县| 和田县| 永吉县| 青岛市| 扶绥县| 双峰县| 樟树市|