hibernate基于外键的单向一对一

单向一对一:通过控制单向多对一中多的一端唯一,有此便形成了单向一对一

配置hibernate环境配置

实体类

public class Student {
	private Integer id;
	private String name;
	private Teacher teacher;
	
	public Teacher getTeacher() {
		return teacher;
	}
	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}
	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
	}
	
}
public class Teacher {
	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;
	}
	
	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>
			<!-- 通过控制多的一方唯一,实现一对一 -->
			<many-to-one name="teacher" column="tid"></many-to-one>
		</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>
	</class>
</hibernate-mapping>

测试代码

public class HibernateTest {

	@Test
	public void testGet() {
		Session session = null;
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			
			Student student = (Student) session.get(Student.class, 3);
			Teacher teacher = student.getTeacher();
			System.out.println(teacher);
			
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}
}

 

posted @ 2019-11-15 17:09  Steven-Russell  阅读(4)  评论(0编辑  收藏  举报  来源