yxhxj2006

          常用鏈接

          統(tǒng)計(jì)

          最新評論

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

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

          1):xml配置:hibernate.cfg.xml (放到src目錄下)和實(shí)體配置類: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í)體配置文件來自動(dòng)生成表(只能生成表).

          -->

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

           

           // 實(shí)體配置類

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

              </session-factory>

          </hibernate-configuration>

           

          (2): 實(shí)體配置類: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類和實(shí)體測試類)

          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;

              }

          }


          實(shí)體測試類:
          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();         //開始事務(wù)

                 

                  Person person = new Person();

                  person.setUsername("何小景");

                  person.setAge(26);

                  session.save(person);

                 

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

              }

          }


           

          4):注解方式:

          注解的方式與xml很很多類似:

          首先是需要加入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í)體類:

               即把:<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í)體類與表進(jìn)行映射。而采用在實(shí)體類中進(jìn)行注解。

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

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

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

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

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

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

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

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

          @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")                                 // 類屬性對應(yīng)著表字段

              public int getId() {

                 return id;

              }

              public void setId(int id) {

                 this.id = id;

              }

             

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

              public String getUsername() {

                 return username;

              }

             

              public void setUsername(String username) {

                 this.username = username;

              }
              

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

                 return age;

              }

              public void setAge(int age) {

                 this.age = age;

              }

             

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

          評論

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

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

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

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

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

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

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

          sa  回復(fù)  更多評論   


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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 理塘县| 中超| 华亭县| 滨海县| 武宣县| 加查县| 凤翔县| 东丽区| 高唐县| 花莲县| 郑州市| 石城县| 洛南县| 中山市| 江华| 财经| 临潭县| 高清| 泸州市| 汤阴县| 珲春市| 曲沃县| 咸阳市| 永川市| 柳河县| 黎平县| 乐清市| 松潘县| 绥中县| 商水县| 广河县| 武强县| 马关县| 呼伦贝尔市| 寻乌县| 濮阳市| 苍山县| 华宁县| 雷波县| 慈利县| 谢通门县|