日出星辰

          Hibernate學(xué)習(xí)之一對(duì)多關(guān)聯(lián)

          注意事項(xiàng):

          1.單向一對(duì)多
             只需在“一”放進(jìn)行配置
          2.雙向一對(duì)多
             需要在關(guān)聯(lián)雙方都加以配置,而且需要在一的一方設(shè)置inverse=true

          首先是實(shí)體類

          TAddress.java(多的一方)

          public class TAddress implements Serializable {
          
          	private static final long serialVersionUID = 1121137857691229229L;
          	private Integer id;
          	private String address;
          	private String zipcode;
          	private String tel;
          	private String type;
          	private TUser user;    //必須有
          
          	............
          }
          

          TUser.java(一的一方)

          public class TUser implements Serializable {
          
          	private static final long serialVersionUID = 1224691192698621789L;
          	private Integer id;
          	private Integer age;
          	private String name;
          	@SuppressWarnings("rawtypes")
          	private Set address = new HashSet();    //多的一方放在集合中
                     
                       ....................
          }
          

          然后是各個(gè)實(shí)體類的配置文件

          TAddress.hbm.xml

           

          <?xml version="1.0"?>
          <!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"
          >
          <!-- 一對(duì)多 -->
          <hibernate-mapping>
          <class name="com.model.TAddress" table="t_address"
          dynamic-update
          ="false" dynamic-insert="false">

          <id name="id" type="java.lang.Integer" column="id" unsaved-value="0">
          <generator class="native" />
          </id>

          <property name="address" column="address" type="string" />
          <property name="tel" column="tel" type="string" />
          <property name="zipcode" column="zipcode" type="string" />
          <property name="type" column="type" type="string" />

          <!-- 必須有many-to-one 否則關(guān)聯(lián)字段(user_id)為null -->
          <many-to-one name="user"
          class
          ="com.model.TUser"
          cascade
          ="none"
          outer-join
          ="auto"
          update
          ="true"
          insert
          ="true"
          access
          ="property"
          column
          ="user_id"
          not-null
          ="true">
          </many-to-one>
          </class>
          </hibernate-mapping>

           TUser.hbm.xml

          <?xml version="1.0"?>
          <!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"
          >
          <!-- 一對(duì)多 外鍵關(guān)聯(lián) -->
          <!-- Select from TUser where id=1 Select from TUser where id=1 to Select
          from TUser where id=1 or id=2
          -->
          <!-- batch-size 批量加載機(jī)制 可以自定義每次批量加載的數(shù)量 -->
          <hibernate-mapping>
          <class name="com.model.TUser" table="t_user" dynamic-update="true"
          >

          <id name="id" type="java.lang.Integer" column="id" unsaved-value="0">
          <generator class="native" />
          </id>

          <property name="name" column="name" />
          <property name="age" column="age" />
          <set name="address" table="t_address" cascade="all" order-by="zipcode asc"
          lazy
          ="true" inverse="true">
          <key column="user_id" /><!-- 確定關(guān)聯(lián)的外鍵列 -->
          <one-to-many class="com.model.TAddress" />
          </set>
          </class>
          </hibernate-mapping>

          其次是hibernate.cfg.xml

          <?xml version='1.0' encoding='utf-8'?>
          <!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 2.0//EN"

          "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd"
          >

          <hibernate-configuration>

          <session-factory>

          <!-- properties -->
          <!-- 數(shù)據(jù)庫(kù)URL -->
          <property name="hibernate.connection.url">jdbc:mysql://localhost/onetomany</property>
          <!-- 數(shù)據(jù)庫(kù)JDBC驅(qū)動(dòng) -->
          <property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
          <!-- 數(shù)據(jù)庫(kù)用戶名 -->
          <property name="hibernate.connection.username">root</property>
          <!-- 數(shù)據(jù)庫(kù)密碼 -->
          <property name="hibernate.connection.password">hello</property>
          <!-- 數(shù)據(jù)庫(kù)方言 -->
          <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
          <!-- 是否日志調(diào)試 -->
          <property name="show_sql">true</property>
          <!-- 是否使用數(shù)據(jù)庫(kù)外連接 -->
          <property name="use_outer_join">true</property>
          <!-- 事務(wù)管理 使用JDBC Transaction(使用JTA會(huì)報(bào)錯(cuò)) -->
          <property name="transaction.factory_class">
          net.sf.hibernate.transaction.JDBCTransactionFactory
          </property>
          <!-- 指定hibernate每次提交的SQL數(shù)量 對(duì)批量操作的性能提升幫助很大!!!!!!!!!!!!! -->
          <property name="hibernate.jdbc.batch_size">25</property>
          <!-- 映射文件配置,配置文件名必須包含其相對(duì)于根的全路徑 -->
          <mapping resource="com/model/TUser.hbm.xml" />
          <mapping resource="com/model/TAddress.hbm.xml" />

          </session-factory>

          </hibernate-configuration>

          測(cè)試代碼(部分)

          增加

          public void testSave(){
          		try {
          			Transaction tx=session.beginTransaction();
          			
          //			TUser user=(TUser) session.load(TUser.class, 1);
          			
          			TUser user=new TUser();
          			user.setName("zhangsan");
          			user.setAge(20);
          			
          			TAddress address=new TAddress();
          			address.setAddress("jingsan");
          			address.setTel("1361380");
          			address.setZipcode("45000");
          			address.setType("java");
          			address.setUser(user); //設(shè)置關(guān)聯(lián)的TUser對(duì)象
          			user.getAddress().add(address);
          			
          			session.save(user);   //級(jí)聯(lián)更新
          			tx.commit();
          		} catch (HibernateException e) {
          			e.printStackTrace();
          		}
          	}
          

          查詢

          	public void testLoad(){
          		try {
          			Transaction tx=session.beginTransaction();
          			String hql="from TUser where name='zhangsan'";
          			List list=session.createQuery(hql).list();
          			System.out.println("-------------1------------");
          			Iterator iter=list.iterator();
          			while(iter.hasNext()){
          				TUser user=(TUser) iter.next();
          				System.out.println("--------------2------------");
          				System.out.println("user.name="+user.getName());
          				System.out.println("--------------3------------");
          				System.out.println("user.address="+user.getAddress().size());
          				System.out.println("--------------4------------");
          			}
          		} catch (HibernateException e) {
          			e.printStackTrace();
          		}
          		
          	}
          

          批量插入(可以提高性能)

           實(shí)現(xiàn)機(jī)制:如果使用了批量加載機(jī)制,hibernate在進(jìn)行數(shù)據(jù)查詢操作前,會(huì)自動(dòng)在當(dāng)前session中尋找是否還存在
           其他同類型待加載的數(shù)據(jù),如果有,則將其查詢條件合并在當(dāng)前的select語句中一并提交,這樣,通過
           一次數(shù)據(jù)庫(kù)操作即完成了多個(gè)讀取任務(wù)。

          //批量插入操作性能優(yōu)化  通過配置<property name="hibernate.jdbc.batch_size">25</property>
          	public void testBatchInsert(){
          		long start=System.currentTimeMillis();
          		this.importUserList();
          		long end=System.currentTimeMillis();
          		System.out.println("批量插入花費(fèi)時(shí)間是"+(end-start));
          	}
          	public void importUserList(){
          		try {
          			Transaction tx=session.beginTransaction();
          			for(int i=0;i<10000;i++){
          				TUser user=new TUser();
          				user.setName("user"+i);
          				session.save(user);
          				if(i%25==0){    //以每25個(gè)數(shù)據(jù)作為一個(gè)處理單元
          					session.flush();
          					session.clear();
          				}
          			}
          			tx.commit();
          		} catch (HibernateException e) {
          			e.printStackTrace();
          		}
          	}
          


           

           

           

           

           

           

           

          posted on 2011-08-23 11:02 日出星辰 閱讀(64) 評(píng)論(0)  編輯  收藏


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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 神农架林区| 常德市| 林周县| 绥芬河市| 宾阳县| 莱西市| 高清| 闽清县| 古丈县| 外汇| 时尚| 徐州市| 仁怀市| 清涧县| 都兰县| 阳泉市| 太原市| 滦南县| 措勤县| 德令哈市| 石棉县| 平阴县| 泊头市| 西城区| 平乐县| 磴口县| 安岳县| 富阳市| 彩票| 乐安县| 普兰县| 静乐县| 铜梁县| 兰溪市| 四会市| 成安县| 延吉市| 津市市| 北海市| 田林县| 罗定市|