熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

Hibernate一對多雙向映射及樂觀鎖使用

2022-06-13   來源: Java開源技術 

  在Hibernate關聯關系映射實例速查一文中通過myeclipse快速做出了Hibernate各種映射的示例時隔快一年了但是還是有博友向我索要工程源碼很遺憾的是已經找不到了但找到一了一個測試代碼對雙向關聯和樂觀鎖的測試其實映射類型很多搞清楚一對多基本上所有的映射就搞明白了一對一也是一對多的特例而已多對多也可以轉換為一對多和多對一並且實際中很少用到多對多

  還是老規矩因為是測試代碼幾乎全部是myeclipse生成的我稍作了修改並且應博友阿飛的留言我做了詳細的注釋

  例子兩部分
    一對多雙向映射模型是班級-學生模型兩個實體分別是Tclass和Student
    樂觀鎖的是使用版本分別使用遞增整數和時間戳兩個實體分別是Foo和Bar

  Tclass實體及其映射
    public class Tclass implements javaioSerializable {

  // Fields

  private Long cid;

  private String cname;

  private Set students = new HashSet();

  // Constructors
        // Property accessors
       

  public String toString() {
            return Tclass{ +
                    cid= + cid +
                    cname= + cname + \ +
                    };
        }
    }

  <hibernatemapping>
        <class name=stuonemanypojoTclass table=tclass>
            <id name=cid type=javalangLong>
                <column name=cid/>
                <generator class=native/>
            </id>
            <property name=cname type=javalangString>
                <column name=cname length= notnull=true/>
            </property>
            <! set元素屬性說明
               name=students 設置表示多個學生的變量名
               inverse=true 關系控制反轉不掌握主控權表示Tclass不控制與Student關聯關系而是將這種關聯控制的權利轉給Student
               cascade=all 表示級聯操作操作班級的時候對班級關聯的學生也做同樣的操作
               lazy=true 查詢班級的時候延遲查詢班級下的學生
            >
            <set name=students inverse=true cascade=all lazy=true>
                <key>
                    <!
                        name=fk_cid 指定關聯的外鍵列
                        notnull=true 說明這個外間列不能為空多余的
                    >
                    <column name=fk_cid notnull=true/>
                </key>
                <! 指定所關聯的類 >
                <onetomany class=stuonemanypojoStudent/>
            </set>
        </class>
    </hibernatemapping>

  Student實體及其映射
    public class Student implements javaioSerializable {

  // Fields

  private Long sid;

  private Tclass tclass;

  private String sname;

  // Constructors
        // Property accessors
       

  public String toString() {
            return Student{ +
                    sid= + sid +
                    sname= + sname + \ +
                    };
        }
    }

  <hibernatemapping>
        <class name=stuonemanypojoStudent table=student>
            <id name=sid type=javalangLong>
                <column name=sid />
                <generator class=native />
            </id>
            <! 表示多個Student關聯一個Tclass >
            <!
                name=tclass 關聯的成員變量名;
                class=stuonemanypojoTclass 表示所關聯的類;
                fetch=select 查詢策略有兩個選項select和join
              select表示通過外聯接來進行查詢查詢速度稍慢但消耗資源少;
              join表示通過內連接來查詢速度快但消耗資源多
             >
            <manytoone name=tclass
                class=stuonemanypojoTclass
                fetch=select>
                <! 指定關聯的外鍵列 >
                <column name=fk_cid notnull=true />
            </manytoone>
            <property name=sname type=javalangString>
                <column name=sname length= notnull=true />
            </property>
        </class>
    </hibernatemapping>

  測試班級學生模型
    public class Test {

  /**
         * @param args
         */
        public static void main(String[] args) {
            testSave();
    //        testDeleteTclass();

  }

  public static void testSave() {
            Tclass c = new Tclass();
            csetCname(某班級);
            Student s = new Student();
            Student s = new Student();
            ssetSname(張三);
            ssetTclass(c);
            ssetSname(李四);
            ssetTclass(c);
            cgetStudents()add(s);
            cgetStudents()add(s);

  Session session = HibernateSessionFactorygetSession();
            Transaction tx = sessionbeginTransaction();
            sessionsave(c);
            mit();
            sessionclose();
        }

  public static void testUpdateClass() {
            Systemoutprintln(正在調用testUpdateClass());
            Session session = HibernateSessionFactorygetSession();
            Tclass c = (Tclass) sessionload(Tclassclass LongvalueOf(L));
            Systemoutprintln(c);
            csetCname(班級更名);
            sessionbeginTransaction(mit();
        }


        public static void testUpdateStudent() {
            Systemoutprintln(正在調用testUpdateStudent());
            Session session = HibernateSessionFactorygetSession();
            Tclass c = (Tclass) sessionload(Tclassclass LongvalueOf(L));
            Student s = (Student) sessionload(Studentclass LongvalueOf(L));
            ssetSname(學生改名換姓王八);
            ssetTclass(c);
            Systemoutprintln(c);
            Systemoutprintln(s);
            sessionbeginTransaction(mit();
            Systemoutprintln(s);
            Systemoutprintln(sgetTclass());
        }

  public static void testDeleteStudent() {
            Systemoutprintln(正在調用testDelete());
            Session session = HibernateSessionFactorygetSession();
            Student s = (Student) sessionload(Studentclass LongvalueOf(L));
            Systemoutprintln(s);
            Systemoutprintln(sgetTclass());
            sessiondelete(s);
            sessionbeginTransaction(mit();
        }

  public static void testDeleteTclass() {
            Systemoutprintln(正在調用testDelete());
            Session session = HibernateSessionFactorygetSession();
            Tclass c = (Tclass) sessionload(Tclassclass LongvalueOf(L));
            Systemoutprintln(c);
            sessiondelete(c);
            sessionbeginTransaction(mit();
        }

  public static void testQueryClass() {
            Systemoutprintln(正在調用testQueryClass());
            Session session = HibernateSessionFactorygetSession();
            Tclass c = (Tclass) sessionload(Tclassclass new Long());
            Systemoutprintln(c);
            Systemoutprintln(cgetStudents());

  }

  public static void testQueryStudent() {
            Systemoutprintln(正在調用testQueryStudent());
            Session session = HibernateSessionFactorygetSession();
            Student s = (Student) sessionload(Studentclass new Long());
            Systemoutprintln(s);
            Systemoutprintln(sgetTclass());
        }
    }

  下面是樂觀鎖的使用
    基於整數的版本控制

  Foo實體和映射文件
    public class Foo implements javaioSerializable {

  // Fields

  private Long pid;

  private Integer version;

  private String name;

  // Constructors
        // Property accessors
       

  public String toString() {
            return Foo{ +
                    pid= + pid +
                    version= + version +
                    name= + name + \ +
                    };
        }
    }

  <hibernatemapping>
        <class name=stuonemanypojoFoo table=foo
               optimisticlock=version>
            <id name=pid type=javalangLong>
                <column name=pid />
                <generator class=native />
            </id>
            <! 版本控制字段必須在id後配置 >
            <version name=version type=javalangInteger>
                <column name=version />
            </version>
            <property name=name type=javalangString>
                <column name=name length= notnull=true />
            </property>
        </class>
    </hibernatemapping>

  測試
    public class TestFoo {

  /**
      * @param args
      */
        public static void main(String[] args) {
      testSave();

  }
        public static void testSave(){
      Foo foo = new Foo(foo);

  Session session = HibernateSessionFactorygetSession();
      sessionsave(foo);
      sessionbeginTransaction(mit();
            sessionclose();
        }
    }

  基於時間戳的版本控制
    public class Bar implements javaioSerializable Comparable {

  // Fields

  private Long id;
        private Date timestamp;
        private String name;

  // Constructors
        // Property accessors
       

  public String toString() {
            return Bar{ +
                    id= + id +
                    timestamp= + timestamp +
                    name= + name + \ +
                    };
        }

  /**
         * 排序接口方法實現為了能對查詢結果按照id的大小進行排序
         * @param o 排序對象
         * @return 比較值
         */
        public int compareTo(Object o) {
            Bar bar = (Bar) o;
            Long res = thisid bargetId();
            return resintValue();
        }
    }

  <hibernatemapping>
        <class name=stuonemanypojoBar table=bar optimisticlock=version>
            <id name=id type=javalangLong>
                <column name=id />
                <generator class=native />
            </id>
            <version name=timestamp type=javautilDate>
                <column name=timestamp length= notnull=true />
            </version>
            <property name=name type=javalangString>
                <column name=name length= notnull=true />
            </property>
        </class>
    </hibernatemapping>

  public class TestBar {
        public static void main(String args[]) {
            testUpdateBar();
            testQueryBar();
        }

  public static void testSaveBar() {
            Bar bar = new Bar(bar);
            Session session = HibernateSessionFactorygetSession();
            sessionsave(bar);
            sessionbeginTransaction(mit();
            sessionclose();
        }

  public static void testQueryBar() {
            Session session = HibernateSessionFactorygetSession();
            String hql = from Bar;
            Query query = sessioncreateQuery(hql);
            List<Bar> barList = querylist();
            Collectionssort(barList);
            for (Bar bar : barList) {
                Systemoutprintln(bargetId() + :\t + bargetTimestamp()getTime());
            }
            sessionclose();
        }

  public static void testUpdateBar() {
            Session session = HibernateSessionFactorygetSession();
            String hql = from Bar;
            Query query = sessioncreateQuery(hql);
            List<Bar> barList = querylist();
            for (Bar bar : barList) {
                barsetName(newBar);
            }
            sessionbeginTransaction(mit();
            sessionclose();
        }
    }

  public class TestStack {
        public static void main(String args[]){
            test();
        }
        public static void  test(){
            Stack stack = new Stack();
            String s= ;
            String s=;
            String s= ;
            String s= ;
            stackpush(s);
            stackpush(s);
            stackpush(s);
            stackpush(s);

  for(;!stackisEmpty();){
                Systemoutprintln(stackpop());
            }

  //for語句先判斷是否符合條件然後確定是否執行循環
            for(int i=;i>;i){
                Systemoutprintln(>>> +i);
            }
        }
    }

  下面是SessionFactory工具和hibernate配置文件
    import orghibernateHibernateException;
    import orghibernateSession;
    import orghibernatecfgConfiguration;

  /**
    * Configures and provides access to Hibernate sessions tied to the
    * current thread of execution  Follows the Thread Local Session
    * pattern see {@link }
    */
    public class HibernateSessionFactory {

  /**
         * Location of hibernatecfgxml file
         * Location should be on the classpath as Hibernate uses
         * #resourceAsStream style lookup for its configuration file
         * The default classpath location of the hibernate config file is
         * in the default package Use #setConfigFile() to update
         * the location of the configuration file for the current session
         */
        private static String CONFIG_FILE_LOCATION = /hibernatecfgxml;
        private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
        private  static Configuration configuration = new Configuration();
        private static orghibernateSessionFactory sessionFactory;
        private static String configFile = CONFIG_FILE_LOCATION;

  static {
            try {
          nfigure(configFile);
          sessionFactory = configurationbuildSessionFactory();
      } catch (Exception e) {
          Systemerr
            println(%%%% Error Creating SessionFactory %%%%);
          eprintStackTrace();
      }
        }
        private HibernateSessionFactory() {
        }

  /**
         * Returns the ThreadLocal Session instance  Lazy initialize
         * the <code>SessionFactory</code> if needed
         *
         *  @return Session
         *  @throws HibernateException
         */
        public static Session getSession() throws HibernateException {
            Session session = (Session) threadLocalget();

  if (session == null || !sessionisOpen()) {
          if (sessionFactory == null) {
        rebuildSessionFactory();
          }
          session = (sessionFactory != null) ? sessionFactoryopenSession()
            : null;
          threadLocalset(session);
      }

  return session;
        }

  /**


         *  Rebuild hibernate session factory
         *
         */
        public static void rebuildSessionFactory() {
      try {
          nfigure(configFile);
          sessionFactory = configurationbuildSessionFactory();
      } catch (Exception e) {
          Systemerr
            println(%%%% Error Creating SessionFactory %%%%);
          eprintStackTrace();
      }
        }

  /**
         *  Close the single hibernate session instance
         *
         *  @throws HibernateException
         */
        public static void closeSession() throws HibernateException {
            Session session = (Session) threadLocalget();
            threadLocalset(null);

  if (session != null) {
                sessionclose();
            }
        }

  /**
         *  return session factory
         *
         */
        public static orghibernateSessionFactory getSessionFactory() {
      return sessionFactory;
        }

  /**
         *  return session factory
         *
         *    session factory will be rebuilded in the next call
         */
        public static void setConfigFile(String configFile) {
      HibernanfigFile = configFile;
      sessionFactory = null;
        }

  /**
         *  return hibernate configuration
         *
         */
        public static Configuration getConfiguration() {
      return configuration;
        }

  }

  <?xml version= encoding=UTF?>
    <!DOCTYPE hibernateconfiguration PUBLIC
              //Hibernate/Hibernate Configuration DTD //EN
              configurationdtd>

  <! Generated by MyEclipse Hibernate Tools                   >
    <hibernateconfiguration>

  <sessionfactory>
      <property name=connectionusername>root</property>
      <property name=connectionurl>
          jdbc:mysql://localhost:/testdb
      </property>
      <property name=dialect>
          orghibernatedialectMySQLDialect
      </property>
      <property name=nnectionprofile>
          commysqljdbcDriver
      </property>
      <property name=connectionpassword>leizhimin</property>
      <property name=connectiondriver_class>
          commysqljdbcDriver
      </property>
      <property name=show_sql>true</property>
      <!<property name=format_sql>true</property>>
            <property name=hbmddlauto>create</property>

  <mapping resource=stu/onemany/pojo/Tclasshbmxml />
      <mapping resource=stu/onemany/pojo/Studenthbmxml />
      <mapping resource=stu/onemany/pojo/Foohbmxml></mapping>
      <mapping resource=stu/onemany/pojo/Barhbmxml />

  </sessionfactory>

  </hibernateconfiguration>

  數據庫用的是mysqlsql腳本我導出了一份如下
    /*
    SQLyog Enterprise MySQL GUI v
    MySQL communitynt : Database testdb
    *********************************************************************
    */

  /*! SET NAMES utf */;

  /*! SET SQL_MODE=*/;

  /*! SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS FOREIGN_KEY_CHECKS= */;
    /*! SET @OLD_SQL_MODE=@@SQL_MODE SQL_MODE=NO_AUTO_VALUE_ON_ZERO */;

  create database if not exists testdb;

  USE testdb;

  /*Table structure for table bar */

  DROP TABLE IF EXISTS bar;

  CREATE TABLE bar (
      id bigint() NOT NULL auto_increment
      timestamp datetime NOT NULL
      name varchar() NOT NULL
      PRIMARY KEY  (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=gbk;

  /*Table structure for table foo */

  DROP TABLE IF EXISTS foo;

  CREATE TABLE foo (
      pid bigint() NOT NULL auto_increment
      version int() NOT NULL
      name varchar() NOT NULL
      PRIMARY KEY  (pid)
    ) ENGINE=InnoDB DEFAULT CHARSET=gbk;

  /*Table structure for table student */

  DROP TABLE IF EXISTS student;

  CREATE TABLE student (
      sid bigint() NOT NULL auto_increment
      fk_cid bigint() NOT NULL
      sname varchar() NOT NULL
      PRIMARY KEY  (sid)
      KEY FKFFEBAA (fk_cid)
      CONSTRAINT FKFFEBAA FOREIGN KEY (fk_cid) REFERENCES tclass (cid)
    ) ENGINE=InnoDB AUTO_INCREMENT= DEFAULT CHARSET=gbk;

  /*Table structure for table tclass */

  DROP TABLE IF EXISTS tclass;

  CREATE TABLE tclass (
      cid bigint() NOT NULL auto_increment
      cname varchar() NOT NULL
      PRIMARY KEY  (cid)
    ) ENGINE=InnoDB AUTO_INCREMENT= DEFAULT CHARSET=gbk;

  /*! SET SQL_MODE=@OLD_SQL_MODE */;
    /*! SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;

  具體測試運行的結果運行下即可看到


From:http://tw.wingwit.com/Article/program/Java/ky/201311/27943.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.