hibernate单向一对多
配置hibernate环境
实体类
package com.wd.pojo;
public class Student {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
public Student(String name) {
super();
this.name = name;
}
public Student(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
}
package com.wd.pojo;
import java.util.HashSet;
import java.util.Set;
public class Teacher {
private Integer id;
private String name;
private Set<Student> stuSet =new HashSet<>();//此处指定映射Student,注意添加get/set方法
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Student> getStuSet() {
return stuSet;
}
public void setStuSet(Set<Student> stuSet) {
this.stuSet = stuSet;
}
public Teacher(Integer id, String name, Set<Student> stuSet) {
super();
this.id = id;
this.name = name;
this.stuSet = stuSet;
}
public Teacher(String name, Set<Student> stuSet) {
super();
this.name = name;
this.stuSet = stuSet;
}
public Teacher() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Teacher [id=" + id + ", name=" + name + "]";
}
}
映射文件
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.wd.pojo.Student" table="t_student">
<id name="id" column="id">
<generator class="identity"></generator>
</id>
<property name="name" column="name" length="50"></property>
</class>
</hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.wd.pojo.Teacher" table="t_teacher">
<id name="id" column="id">
<generator class="identity"></generator>
</id>
<property name="name" column="name" length="50" ></property>
<set name="stuSet">
<!-- 指定外键,可以通过此键值查询出t_student中的信息 -->
<!-- column指定的外键值必须是t_student中已经有的字段,否则返回[] -->
<key column="tid" not-null="true"/>
<one-to-many class="com.wd.pojo.Student"/>
</set>
</class>
</hibernate-mapping>
测试代码
public class HibernateTest {
@Test
public void testGet() {
Session session = null;
try {
session = HibernateUtil.getSession();
session.beginTransaction();
Teacher teacher = (Teacher) session.get(Teacher.class, 2);
// System.out.println(teacher);
Set<Student> stuSet = teacher.getStuSet();
System.out.println(stuSet);
for (Student student : stuSet) {
System.out.println(student);
}
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
}