数据库:两张表,在多方加键
一、编写一方实体类
二、编写多方实体类
在多方加一方外键,即属性,再定义@ManyToOne即可
三、在hibernate.cfg.xml映射配置
四、测试代码
五、测试结果
xml方式:
一。编写实体类如上
二。配置一方Group.hbm.xml
三。配置多方User.hbm.xml
配置多方"属性group"对应列
四。测试如上
一、编写一方实体类
package org.hibernate.tutorial.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Group {
private int id;
private String name;
@Id
@GeneratedValue
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
二、编写多方实体类
package org.hibernate.tutorial.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class User {
private int id;
private String name;
private Group group;
@Id
@GeneratedValue
public int getId() {
return id;
}
@ManyToOne
@JoinColumn(name="GroupID")
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
在多方加一方外键,即属性,再定义@ManyToOne即可
三、在hibernate.cfg.xml映射配置
<mapping class="org.hibernate.tutorial.domain.Group"/>
<mapping class="org.hibernate.tutorial.domain.User"/>
四、测试代码
public class OneToOneORMappingTest {
public static void main(String[] args) {
new SchemaExport(new AnnotationConfiguration().configure("/hibernate.cfg.xml")).create(true, false);
}
}
五、测试结果
create table Group (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)
create table User (
id integer not null auto_increment,
name varchar(255),
GroupID integer,
primary key (id)
)
alter table User
add index FK_d3xpiqkj77d392pew07ptibhp (GroupID),
add constraint FK_d3xpiqkj77d392pew07ptibhp
foreign key (GroupID)
references Group (id)
xml方式:
一。编写实体类如上
二。配置一方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="org.hibernate.tutorial.domain">
<class name="Group" table="Group">
<id name="id" column="group_Id">
<generator class="native"/>
</id>
<property name="name"></property>
</class>
</hibernate-mapping>
三。配置多方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="org.hibernate.tutorial.domain">
<class name="User" table="User">
<id name="id" column="User_ID">
<generator class="native"/>
</id>
<property name="name"></property>
<many-to-one name="group" column="groupId"></many-to-one>
</class>
</hibernate-mapping>
配置多方"属性group"对应列
四。测试如上