多对一单向关联,在多的一方加上一的一方作为外键。在程序里表现为:在多的一方加上一的引用。
小组类Group,用户User:
Group:
package com.oracle.hibernate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="t_group")//group是mysql的关键字,换个名 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:
package com.oracle.hibernate; 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; //多对一 @ManyToOne @JoinColumn(name="groupId")//指定外键名称 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; } }
生成的表:可以看到在User里加了外键
hibernate建表语句:
create table User (
id integer not null auto_increment,
name varchar(255),
groupId integer,
primary key (id)
)
create table t_group (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)
在User里加了外键:
alter table User
add index FK285FEB744AEC3A (groupId),
add constraint FK285FEB744AEC3A
foreign key (groupId)
references t_group (id)