1、很多情况下,hibernate many-to-one 都是通过主键去关联,如下
员工表(t_user):
CREATE TABLE `t_user` (
`id` varchar(50) NOT NULL,
`eno` varchar(10) NOT NULL COMMENT '编号',
`name` varchar(60) NOT NULL COMMENT '姓名',
`photo` varchar(100) DEFAULT NULL COMMENT '图片',
`tel` varchar(20) NOT NULL COMMENT '电话',
`address` varchar(100) NOT NULL COMMENT '地址',
`summary` text NOT NULL COMMENT '简介',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8
请假表(t_leavebill):
CREATE TABLE `t_leavebill` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`days` int(11) DEFAULT NULL,
`content` varchar(255) DEFAULT NULL,
`remark` varchar(255) DEFAULT NULL,
`leaveDate` timestamp NULL DEFAULT NULL,
`state` int(11) DEFAULT NULL,
`user_id` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8
请假表(t_leavebill)中user_id关联的是员工表(t_user)中的id(主键)
Leavebill.java如下:
public class Leavebill implements java.io.Serializable {
private String id;
private Integer days;
....
private User user;
}
Leavebill.hbm.xml如下
<hibernate-mapping>
<class name="com.test.model.Leavebill" table="t_leavebill" >
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="assigned" />
</id>
<property name="days" type="int">
<column name="days" />
</property>
<many-to-one name="user" class="com.test.model.User" fetch="select" lazy="false">
<column name="user_id" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>
2、请假表(t_leavebill)修改结构为:
CREATE TABLE `t_leavebill` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`days` int(11) DEFAULT NULL,
`content` varchar(255) DEFAULT NULL,
`remark` varchar(255) DEFAULT NULL,
`leaveDate` timestamp NULL DEFAULT NULL,
`state` int(11) DEFAULT NULL,
`eno` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8
请假表(t_leavebill)中eno关联的是员工表(t_user)中的eno字段。
Leavebill.java文件不变。
Leavebill.hbm.xml修改如下
<hibernate-mapping>
<class name="com.test.model.Leavebill" table="t_leavebill" >
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="assigned" />
</id>
<property name="days" type="int">
<column name="days" />
</property>
<many-to-one name="user" class="com.test.model.User" property-ref="eno" fetch="select" lazy="false">
<column name="eno" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>
注:many-to-one 添加property-ref=”eno”属性,修改column name=’eno”。
3、property-ref是为了解决遗留系统中实体之间的关联。
默认情况下,把被关联实体主键字段作为关联字段。有了property-ref,就可以
通过它指定被关联实体主键以外的字段作为关联字段。