多对一单向关联(annotation&xml)

数据库:两张表,在多方加键

一、编写一方实体类

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"对应列

四。测试如上
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值