one2many单向
1 1的一方的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.baowei.entity"> <class name="Classroom" table="classroom"> <id name="id"> <generator class="native" /> </id> <property name="name" /> <property name="grade" /> <!-- 使用了lazy=extra之后会稍微智能一些,会根据去的值的不同来判断是调用count和获取投影 --> <set name="stus" lazy="extra"> <key column="mid" /> <!-- key用来指定在对方的外键的名称 --> <one-to-many class="Student" /> <!-- class用来设置列表中的对象类型 --> </set> </class> </hibernate-mapping>
2 关于one2many的测试代码
2.1 测试Add,会发出五条sql,三条插入,两条更新
public void testAdd01() {
Session session = null;
try {
session = HibernateUtil.openSession();
session.beginTransaction();
Student stu1 = new Student();
stu1.setName("猪八戒");
stu1.setNo("001");
Student stu2 = new Student();
stu2.setName("孙悟空");
stu2.setNo("002");
session.save(stu2);
session.save(stu1);
session.save(stu2);
Classroom c = new Classroom();
c.setGrade(2012);
c.setName("计算机网络技术");
// //设置关联关系
c.getStus().add(stu1);
c.getStus().add(stu2);
session.save(c);
// 此时会发出5条sql,三条查询,两条更新
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
if (session != null)
session.getTransaction().rollback();
} finally {
// HibernateUtil.close(session);
}
}
2.2 测试懒加载-----再用到的时候才回去发出sql语句
2.3 关于lazy=extra,会智能的用一些sql语句去查询,如果输出的是int类型,会去select count(*)
public void testAdd02() {
Session session = null;
try {
session = HibernateUtil.openSession();
session.beginTransaction();
Classroom c = (Classroom) session.load(Classroom.class, 1);
System.out.println(c.getStus().size());
//如果使用了 lazy=extra,sql语句会进行一些优化
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
if (session != null)
session.getTransaction().rollback();
} finally {
HibernateUtil.close(session);
}
}
2.4