基于Annotation 的多对一ManyToOne双向和基于XML配置多对一双向
基于Annotation:
package com.stark.hibernate.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="t_group")
public class Group {
private int groupId ;
private String groupName;
private Set<User> users= new HashSet<User>();
@Id
@GeneratedValue
public int getGroupId() {
return groupId;
}
public void setGroupId(int id) {
this.groupId = id;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String name) {
this.groupName = name;
}
/**
* One 代表Group,Many代表User ,我们需要在多的一方添加外键,如果不添加@JoinColumn(name="groupId"),将会生成一张t_group_t_user的中间表
* 否则将会在user表中自动添加groupId字段
* @return
*/
@OneToMany(mappedBy="group",cascade = { CascadeType.ALL})
@JoinColumn(name="groupId")
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
PS:需要在Group表中添加OneToMany(mappedBy="group"),目的就是外键由User表来指定,如果不添加,将会在User中自动添加一条t_group_id,这是冗余字段的
package com.stark.hibernate.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="t_user")
public class User {
private int userId;
private String userName;
private Group group;
@Id
@GeneratedValue
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
/**
*
* 只需在多方User中添加一个Group同时添加注解@ManyToOne即可(Many代表User,One代表Group)
*/
@ManyToOne
@JoinColumn(name="groupId")
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
}
生成DDL语句为:
create table t_group (groupId integer not null auto_increment, groupName varchar(255), primary key (groupId))
create table t_user (userId integer not null auto_increment, userName varchar(255), groupId integer, primary key (userId))
alter table t_user add index FKCB63CCB65F00FCD6 (groupId), add constraint FKCB63CCB65F00FCD6 foreign key (groupId) references t_group (groupId)
基于XML:
去掉Group和UserJavaBean中所有@注解
Group.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.stark.hibernate.model">
<class name="Group" table="t_group">
<id name="groupId" >
<generator table="t_user">
<id name="userId">
<generator />
<many-to-one name="group" column="groupId" cascade="all" ></many-to-one>
</class>
</hibernate-mapping>
生成DDL语句:
与用Annotation生成的是一样的。