Hibernate 映射关系
映射关系通俗点来说
- 单向:一边写,一边不写
- 双向:两边都写
一、一对一(单向)
Address实体类:不用配置
User实体类:编写配置
public class User {
....
private Address address;
}
<hibernate-mapping>
<class name="priv.linyu.hibernate.entity.User" table="tb_user" schema="db_test">
....
<!-- 一个地址对应一个用户 -->
<one-to-one name="address" constrained="true" />
</class>
</hibernate-mapping>
二、多对一(单向)
User实体类:不用配置
Book实体类:编写配置
public class Book {
...
private User user;
}
<hibernate-mapping>
<class name="priv.linyu.hibernate.entity.Book" table="tb_book" schema="db_test">
...
<many-to-one name="user" column="user_id" cascade="all" />
</class>
</hibernate-mapping>
三、一对多(单向)
Student实体类:不用配置
班级实体类:编写配置
public class Clazz {
...
private Set<Student> students = new HashSet<Student>();
}
<class name="priv.linyu.hibernate.entity.Clazz" table="tb_clazz" schema="db_test">
...
<set name="students">
<key column="clazz_id" not-null="true" />
<one-to-many class="priv.linyu.hibernate.entity.Student"/>
</set>
</class>
四、多对多(单向)
Student实体类:不用配置
课程实体类:编写配置
public class Course {
...
private Set<Student> students = new HashSet<Student>();
}
<class name="priv.linyu.hibernate.entity.Course" table="tb_course">
...
<set name="students" table="tb_course_student">
<key column="course_id" />
<many-to-many column="student_id" class="priv.linyu.hibernate.entity.Student"/>
</set>
</class>
五、一对一(双向)
User实体类:编写配置
public class User {
....
private Address address;
}
<hibernate-mapping>
<class name="priv.linyu.hibernate.entity.User" table="tb_user" schema="db_test">
....
<one-to-one name="address" constrained="true" />
</class>
</hibernate-mapping>
Address实体类:编写配置
public class Address {
...
private User user;
}
<hibernate-mapping>
<class name="priv.linyu.hibernate.entity.Address" table="tb_address" schema="db_test">
...
<one-to-one name="user" />
</class>
</hibernate-mapping>
六、一对多,多对一(双向)
班级实体类:编写配置
public class Clazz {
...
private Set<Student> students = new HashSet<Student>();
}
<class name="priv.linyu.hibernate.entity.Clazz" table="tb_clazz" schema="db_test">
...
<set name="students">
<key column="clazz_id" not-null="true" />
<one-to-many class="priv.linyu.hibernate.entity.Student"/>
</set>
</class>
Student实体类:编写配置
public class Student {
...
private Clazz clazz;
}
<hibernate-mapping>
<class name="priv.linyu.hibernate.entity.Student" table="tb_student" schema="db_test">
...
<many-to-one name="clazz" column="clazz_id" cascade="all"/>
</class>
</hibernate-mapping>
七、常用注解
- @Entity:将一个类声明为一个持久化类
- @Table(name="表名"):为持久化类映射指定表
- @Id:声明了持久化类的标识属性
- @GeneratedValue(strategy=GenerationType.IDENINY)
- AUTO主键由程序控制, 是默认选项
- IDENTITY 主键由数据库生成, 采用数据库自增长, Oracle不支持这种方式
- SEQUENCE 通过数据库的序列产生主键, MYSQL 不支持
- Table 提供特定的数据库产生主键, 该方式更有利于数据库的移植
- @Column(name = "字段名"):将属性映射到列
- @Transient:将忽略这些属性,设置之后,标为不被映射
- @OneToOne:建立持久化类之间的一对一关联
- @OneToMany:建立持久化类之间的一对多关联
- @ManyToOne:建立持久化类之间的多对一关联
- @ManyToMany:建立持久化类之间的多对多关联

浙公网安备 33010602011771号