多对多单向:
Bean:
public class Student implements Serializable { private int id ; private String name ; private Set<Teacher> teachers ; .... } public class Teacher implements Serializable{ private int id ; private String name ; .... }
xml:
Student.hbm.xml: <class name = "Student"> <!-- id是来配置主键 name是类中的哪个属性和主键映射 generator:表示主键的生成策略 --> <id name = "id"> <generator class="native" /> </id> <!-- property是用来把类中的属性和表的字段做一一对应 --> <property name="name" /> <set name="teachers" table="t_s"> <!-- key 会在指定的表中新添加列,外键--> <key column="sid" /> <many-to-many class="Teacher" column="tid" /> </set> </class> Teacher.hbm.xml: <class name = "Teacher"> <!-- id是来配置主键 name是类中的哪个属性和主键映射 generator:表示主键的生成策略 --> <id name = "id"> <generator class="native" /> </id> <property name="name" /> </class>
annotation:
@Entity public class Student implements Serializable { @Id @GeneratedValue public int getId() { return id; } /** * joinColumns 是指定第三张表中的哪个字段引用当前类对应的表的主键 * inverseJoinColumns 是指定第三张表中的哪个字段引用关联的另一张表的主键 * @return */ @ManyToMany @JoinTable(name="ts",joinColumns={ @JoinColumn(name="sid") },inverseJoinColumns={ @JoinColumn(name="tid") }) public Set<Teacher> getTeachers() { return teachers; } } @Entity public class Teacher implements Serializable{ @Id @GeneratedValue public int getId() { return id; } }
多对多双向:
Bean:
public class Student implements Serializable { private int id ; private String name ; private Set<Teacher> teachers ; .... } public class Teacher implements Serializable{ private int id ; private String name ; private Set<Student> stus ; .... }
Xml:
Student.hbm.xml: <class name = "Student"> <!-- id是来配置主键 name是类中的哪个属性和主键映射 generator:表示主键的生成策略 --> <id name = "id"> <generator class="native" /> </id> <!-- property是用来把类中的属性和表的字段做一一对应 --> <property name="name" /> <set name="teachers" table="t_s"> <!-- key 会在指定的表中新添加列,外键--> <key column="sid" /> <many-to-many class="Teacher" column="tid" /> </set> </class> Teacher.hbm.xml: <class name = "Teacher"> <!-- id是来配置主键 name是类中的哪个属性和主键映射 generator:表示主键的生成策略 --> <id name = "id"> <generator class="native" /> </id> <property name="name" /> <set name="stus" table="t_s" cascade="all"> <key column="tid" /> <many-to-many column="sid" class="Student" /> </set> </class>
annotation:
@Entity public class Student implements Serializable { @Id @GeneratedValue public int getId() { return id; } /** * joinColumns 是指定第三张表中的哪个字段引用当前类对应的表的主键 * inverseJoinColumns 是指定第三张表中的哪个字段引用关联的另一张表的主键 * @return */ @ManyToMany @JoinTable(name="ts",joinColumns={ @JoinColumn(name="sid") },inverseJoinColumns={ @JoinColumn(name="tid") }) public Set<Teacher> getTeachers() { return teachers; } } @Entity public class Teacher implements Serializable{ @Id @GeneratedValue public int getId() { return id; } @ManyToMany(mappedBy="teachers") public Set<Student> getStus() { return stus; } }
时间: 2024-11-05 14:57:23