yxhxj2006

          常用鏈接

          統(tǒng)計(jì)

          最新評(píng)論

          Hibernate實(shí)現(xiàn)有兩種配置,xml配置與注釋配置

          hibernate實(shí)現(xiàn)有兩種配置,xml配置與注釋配置。

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

          <?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 表示可以根據(jù)實(shí)體配置文件來(lái)自動(dòng)生成表(只能生成表).

          -->

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

           

           // 實(shí)體配置類(lèi)

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

              </session-factory>

          </hibernate-configuration>

           

          (2): 實(shí)體配置類(lèi):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):測(cè)試類(lèi)(包括獲取SessionFactory類(lèi)和實(shí)體測(cè)試類(lèi))

          SessionFactory類(lèi):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;

              }

          }


          實(shí)體測(cè)試類(lèi):
          PersonManager

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

          public class PersonManager {

              public static void main(String[] args) {

                   createAndStorePerson();

                  HibernateUtil.getSessionFactory().close();

          }

           

              private static void createAndStorePerson() {

                  Session session =                   // 通過(guò)Session工廠(chǎng)獲取Session對(duì)象

          HibernateUtil.getSessionFactory().getCurrentSession();

                  session.beginTransaction();         //開(kāi)始事務(wù)

                 

                  Person person = new Person();

                  person.setUsername("何小景");

                  person.setAge(26);

                  session.save(person);

                 

                  session.getTransaction().commit(); // 提交事務(wù)

              }

          }


           

          4):注解方式:

          注解的方式與xml很很多類(lèi)似:

          首先是需要加入4個(gè)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改為引用實(shí)體類(lèi):

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

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

          2):獲取SessionFactory方式發(fā)生了變化:

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

              改為:SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory()

          3):注解方式不需要在xxx.hbm.xml把實(shí)體類(lèi)與表進(jìn)行映射。而采用在實(shí)體類(lèi)中進(jìn)行注解。

          注意:1):如果實(shí)體類(lèi)屬性名與表字段名不一致的時(shí)候,要么都注解在屬性前,要么都注解在get方法前。不能部分注解在屬性前,部分注解在方法前。

           (2如果實(shí)體類(lèi)屬性名與表字段名一致的時(shí)候,可以部分注解在屬性前,部分注解在方法前。

           (3):如果在實(shí)體類(lèi)中某些屬性不注解:(屬性和get都不寫(xiě)注解),默認(rèn)為表字段名與實(shí)體類(lèi)屬性名一致。

           (4):如果實(shí)體類(lèi)的某個(gè)成員屬性不需要存入數(shù)據(jù)庫(kù)中,使用@Transient 進(jìn)行注解就可以了。即類(lèi)似于:(xxx.hbm.Xml配置中的某些字段不寫(xiě)(就是不需要對(duì)這個(gè)成員屬性進(jìn)行映射))

           (5):表名稱(chēng)可以在實(shí)體類(lèi)前進(jìn)行注解。

           (6所有這些注解在:javax.persistence包下。而不是在hibernate包中。

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

          @Entity                        // 表示為實(shí)體類(lèi)

          @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")   // 自增長(zhǎng)

              @Column(name = "id")                                 // 類(lèi)屬性對(duì)應(yīng)著表字段

              public int getId() {

                 return id;

              }

              public void setId(int id) {

                 this.id = id;

              }

             

              @Column(name="t_username")                       // 類(lèi)屬性對(duì)應(yīng)著表字段

              public String getUsername() {

                 return username;

              }

             

              public void setUsername(String username) {

                 this.username = username;

              }
              

              @Column(name="t_age")                      // 在實(shí)體類(lèi)屬性進(jìn)行注解,類(lèi)屬性對(duì)應(yīng)著表字段
             
          public int getAge() {

                 return age;

              }

              public void setAge(int age) {

                 this.age = age;

              }

             

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

          評(píng)論

          # re: Hibernate實(shí)現(xiàn)有兩種配置,xml配置與注釋配置 2014-05-20 16:35 胡淘

          我想把entity單獨(dú)抽出來(lái)作為一個(gè)公共的模塊,或者說(shuō)一個(gè)單獨(dú)的項(xiàng)目,反正和dao這一層分開(kāi)。那是不是只能用配置文件注解了?  回復(fù)  更多評(píng)論   

          # re: Hibernate實(shí)現(xiàn)有兩種配置,xml配置與注釋配置 2014-08-20 18:01 楊宇

          在一個(gè)文件夾下就行好比說(shuō)你的實(shí)體類(lèi)文件夾是 entity 你只要把所有的類(lèi)名.hbm.xml都放在這個(gè)entity文件夾下就行@胡淘
            回復(fù)  更多評(píng)論   

          # re: Hibernate實(shí)現(xiàn)有兩種配置,xml配置與注釋配置 2015-12-19 16:27 小涂

          這是hibernate的那個(gè)版本(4.3能用嗎)  回復(fù)  更多評(píng)論   

          # re: Hibernate實(shí)現(xiàn)有兩種配置,xml配置與注釋配置[未登錄](méi) 2016-04-15 15:22 sa

          sa  回復(fù)  更多評(píng)論   


          只有注冊(cè)用戶(hù)登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 柯坪县| 固阳县| 股票| 牡丹江市| 襄樊市| 突泉县| 正宁县| 鄄城县| 祥云县| 临潭县| 松江区| 东台市| 新丰县| 吉首市| 青川县| 电白县| 项城市| 无锡市| 台中县| 马关县| 婺源县| 健康| 陆良县| 大丰市| 疏勒县| 雷山县| 西华县| 永宁县| 万安县| 武胜县| 阜平县| 武宁县| 嘉禾县| 云林县| 绩溪县| 武平县| 邹平县| 竹溪县| 许昌市| 湖南省| 南乐县|