User.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.shiryu.otm.User" table="user" batch-size="5"
lazy="false" dynamic-update="true" dynamic-insert="true"
optimistic-lock="version">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<!-- 使用乐观锁 -->
<version name="version" column="version"
type="java.lang.Integer" />
<property name="name" type="java.lang.String">
<column name="name" length="50" />
</property>
<property name="age" type="java.lang.Integer" column="age" lazy="true"/>
<set name="addresses" table="address" cascade="all"
order-by="address desc">
<key column="user_id"></key>
<one-to-many class="com.shiryu.otm.Address" />
</set>
</class>
</hibernate-mapping>
LoadTest.java:
package com.shiryu.otm;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class LoadTest {
// 数据加载方式
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tr = session.beginTransaction();
String hql = "from User where name='zhaiyu'";
List list = session.createQuery(hql).list();
System.out.println("this is query results");
Iterator it = list.iterator();
while (it.hasNext()) {
User user = (User) it.next();
System.out.println(user.getName());
System.out.println(user.getAddresses().size());
}
// 批量加载
String hql2 = "from User where id=1 or id=2";
List list2 = session.createQuery(hql2).list();
System.out.println("this is query results");
Iterator it2 = list.iterator();
while (it2.hasNext()) {
User user1 = (User) it2.next();
System.out.println(user1.getName());
}
}
}