@Entity @Table(name="t_group") public class Group { private int id; private String name; public Group(){ } public Group(String name) { this.name = 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; } }
@Entity @Table(name="t_user") public class User { private int id; private String name; private Group group; public User(){ } public User(String name) { this.name = name; } @ManyToOne //Group不是数据库中的数据类型,所以要用ManyToOne转换 @JoinColumn(name="mygroudid") //在t_user表中生成mygroupid字段 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; } }
2.生成的sql语句:
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),
mygroudid integer,
primary key (id)
)
alter table t_user add index FKCB63CCB6C650D60F (mygroudid), add constraint FKCB63CCB6C650D60F foreign key (mygroudid) references t_group (id)
2.如果不指定JoinColumn,也会生成默认的字段
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 FKCB63CCB69870A148 (group_id), add constraint FKCB63CCB69870A148 foreign key (group_id) references t_group (id)