Hibernate映射关系配置
Posted 对方拒收了你的消息
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate映射关系配置相关的知识,希望对你有一定的参考价值。
多对多单向:
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; } }
以上是关于Hibernate映射关系配置的主要内容,如果未能解决你的问题,请参考以下文章