基于List集合映射

1、 实体类中使用List集合

 public class Grade {
private int id;
private String name;
private List<Student> students = new ArrayList<Student>(0);
}

2、 映射文件

 <hibernate-mapping package="cn.siggy.pojo">
<class name="Grade">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"/>
<list name="students" cascade="all">
<!-- key表示外键 column外键列名-->
<key column="grade_id"></key>
<!-- 在多的一端 产生一列 用来表示顺序 如果不指明列名 默认为 idx
值由hibernate来维护
-->
<list-index column="sort">
</list-index>
<!-- one-to-many 一对多 类Grade 中 students 所表示类型 -->
<one-to-many class="Student"/>
</list>
</class>

3、 测试代码

 @Test
public void testSave() throws HibernateException, SerialException, SQLException{
Configuration cfg = new Configuration().configure();
SessionFactory factory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build());
Session session = null;
Transaction tx = null;
try{
session = factory.openSession();
tx = session.beginTransaction();
Grade grade = new Grade();
grade.setName("基础"); Student stu = new Student();
stu.setName("张三疯");
stu.setAge(22);
Student stu1 = new Student();
stu1.setName("老王");
stu1.setAge(23);
Student stu2 = new Student();
stu2.setName("老李");
stu2.setAge(23);
//关联
grade.getStudents().add(stu);
grade.getStudents().add(stu1);
grade.getStudents().add(stu2);
//保存数据的顺序 是根据外键的配置来决定的
//如果外键不能为null,那么先保存一的一端
//如果外键可以为null,则可以随意保存
session.save(grade);
session.save(stu);
session.save(stu1);
session.save(stu2); tx.commit(); }catch (HibernateException e) {
if(tx!=null)
tx.rollback();
e.printStackTrace();
throw e;
}finally{
HibernateUtil.closeSession();
}
}
@Test
public void testGet(){
Session session = null;
Transaction tx = null;
try{
session = HibernateUtil.getSession();
tx = session.beginTransaction();
//取数据
Grade grade = (Grade)session.get(Grade.class, 1);
System.out.println("gradeName="+grade.getName());
System.out.println("grade所对应的多的一端的数据");
List<Student> list = grade.getStudents();
for(Student stu:list){
System.out.println(stu.getName());
}
tx.commit();
}catch (HibernateException e) {
if(tx!=null)
tx.rollback();
e.printStackTrace();
throw e;
}finally{
HibernateUtil.closeSession();
}
}
上一篇:exit(-1)或者return(-1)为什么shell得到的退出码是255?


下一篇:jdbc报java.lang.ClassNotFoundException: com.mysql.jdbc.Drive