一个组有多个用户,一个用户只能属于一个组。
使用Annotation注解来实现多对一单项关联

Group.java:

package cn.edu.hpu.many2one;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="t_group")
public class Group {
private int id;
private String name;

@Id
@GeneratedValue
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;


@Entity
@Table(name="t_user")
public class User {
private int id;
private String name;
private Group group;

@ManyToOne //核心语句
//@JoinColumn(name="groupid")想改属性名用这个(默认的是group_id)
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
@Id
@GeneratedValue
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;
}

}



在hibernate.cfg.xml中配置:


<mapping class="cn.edu.hpu.many2one.Group"/>
<mapping class="cn.edu.hpu.many2one.User"/>


建表语句:

alter table t_user 

drop

foreign key FKCB63CCB61AEE691B



drop table if exists t_group



drop table if exists t_user



create table t_group (

id integer not null auto_increment,

name varchar(255),

primary key (id)

)



create table t_user (

id integer not null auto_increment,

name varchar(255),

group_id integer,

primary key (id)

)



alter table t_user

add index FKCB63CCB61AEE691B (group_id),

add constraint FKCB63CCB61AEE691B

foreign key (group_id)

references t_group (id)

schema export complete




结果在User表里的group_id属性上加了指向group的id的外键。(如果group_id存的数不是属于group表中数据的任何一个id,那么就不会被保存而报错,这就是外键的精髓)