1.双向关系中使用mappedBy避免生成中间表
(1).只有OneToOne,OneToMany,ManyToMany上才有mappedBy属性,ManyToOne不存在该属性;
(2).mappedBy标签一定是定义在被拥有方(Group),他指向拥有方(User);
@Entity
@Table(name="t_group")
public class Group {
private int id;
private String name;
private Set<User> users = new HashSet<User>();
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;
}
@OneToMany
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
@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
@JoinColumn(name="mygroudid")
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_group_t_user (
t_group_id integer not null,
users_id integer not null,
primary key (t_group_id, users_id),
unique (users_id)
)
create table t_user (id integer not null auto_increment, name varchar(255), mygroudid integer, primary key (id))
alter table t_group_t_user add index FKCFE61C614F1D14B3 (t_group_id), add constraint FKCFE61C614F1D14B3 foreign key (t_group_id) references t_group (id)
alter table t_group_t_user add index FKCFE61C61363448CF (users_id), add constraint FKCFE61C61363448CF foreign key (users_id) references t_user (id)
alter table t_user add index FKCB63CCB6C650D60F (mygroudid), add constraint FKCB63CCB6C650D60F foreign key (mygroudid) references t_group (id)
3.如果在在Group中
@OneToMany(mappedBy="group") //“group”对应User类中的group属性。不能写错
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
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)