Hibernate 對映關係 ---Many2Many 單向關聯
阿新 • • 發佈:2019-01-10
一個學生可以有多個老師,一個老師也可以有多個學生,所以老師和學生之間的關係就是多對多的關係,這樣就需要建立一箇中間的關聯表來儲存關聯資訊。
[java] view plain copy
- package com.pojo;
- public class Student implements java.io.Serializable {
- private
- private String name;
- private Long age;
- private String sex;
- public Student() {
- }
- public Long getId() {
- return this.id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Long getAge() {
- return this.age;
- }
- public void setAge(Long age) {
- this.age = age;
- }
- public String getSex() {
- return this.sex;
- }
- public void setSex(String sex) {
- this.sex = sex;
- }
- }
[java] view plain copy
- package com.pojo;
- import java.util.HashSet;
- import java.util.Set;
- public class Teacher implements java.io.Serializable {
- private static final long serialVersionUID = -7640561034271065452L;
- private Long id;
- private String name;
- private String sourcename;
- //多對多單向關聯
- private Set<Student> students = new HashSet<Student>() ;
- public Teacher() {
- }
- public Long getId() {
- return this.id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getSourcename() {
- return this.sourcename;
- }
- public void setSourcename(String sourcename) {
- this.sourcename = sourcename;
- }
- public Set<Student> getStudents() {
- return students;
- }
- public void setStudents(Set<Student> students) {
- this.students = students;
- }
- }
[xhtml] view plain copy
- <?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">
- <!--
- Mapping file autogenerated by MyEclipse Persistence Tools
- -->
- <hibernate-mapping>
- <class name="com.pojo.Teacher" table="TEACHER" schema="ZM">
- <id name="id" type="java.lang.Long">
- <column name="ID" precision="4" scale="0" />
- <generator class="increment" />
- </id>
- <property name="name" type="java.lang.String">
- <column name="NAME" length="100" />
- </property>
- <property name="sourcename" type="java.lang.String">
- <column name="SOURCENAME" length="100" />
- </property>
- <!--
- 多對多單向關聯,table標識關聯表,key裡面column屬性代表該類(Teacher)在關聯表裡面的鍵是teacher_id
- many-to-many 裡面class屬性是set裡面的型別,後面的column是指該類在關聯表裡面的外來鍵
- outer-join="true" 外連線
- cascade="save-update" 級聯操作
- -->
- <set name="students" table="stutea" outer-join="true" cascade="save—update">
- <key column="teacher_id"></key>
- <many-to-many class="com.pojo.Student" column="student_id"/>
- </set>
- </class>
- </hibernate-mapping>