使用XML来实现多对一单项关联
Group.java:
package cn.edu.hpu.many2one; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; public class Group { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
User.java:
package cn.edu.hpu.many2one; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; public class User { private int id; private String name; private Group group; public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
User.hbm.xml:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.edu.hpu.many2one"> <class name="User" table="x_user" dynamic-update="true"> <!-- 主键 这里的主键名字刚好也是'id'--> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="name"></property> <many-to-one name="group" column="groupId"/> </class> </hibernate-mapping>
Group.hbm.xml:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.edu.hpu.many2one"> <class name="Group" table="x_group" dynamic-update="true"> <!-- 主键 这里的主键名字刚好也是'id'--> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="name"></property> </class> </hibernate-mapping>
在hibernate.cfg.xml中配置:
<mapping resource="cn/edu/hpu/many2one/Group.hbm.xml"/> <mapping resource="cn/edu/hpu/many2one/User.hbm.xml"/>
建表语句:
alter table x_user
drop
foreign key FKD2372F32E3D521A
drop table if exists x_group
drop table if exists x_user
create table x_group (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)
create table x_user (
id integer not null auto_increment,
groupId integer,
primary key (id)
)
alter table x_user
add index FKD2372F32E3D521A (groupId),
add constraint FKD2372F32E3D521A
foreign key (groupId)
references x_group (id)
schema export complete
结果在x_user表里的groupId属性上加了指向group的id的外键。(如果groupId存的数不是属于x_group表中数据的任何一个id,那么就不会被保存而报错,这就是外键的精髓)
转载请注明出处:http://blog.csdn.net/acmman
原文链接:https://www.f2er.com/xml/297202.html