对Jpa中Entity关系映射中mappedBy的理解

时间:2021-07-14 07:07:25

mappedBy 单向关系不需要设置该属性,双向关系必须设置,避免双方都建立外键字段数据库中1对多的关系,关联关系总是被多方维护的即外键建在多方,我们在单方对象的@OneToMany(mappedby="")把关系的维护交给多方对象的属性去维护关系。

对于mappedBy复习下:
a) 只有OneToOne,OneToMany,ManyToMany上才有mappedBy属性,ManyToOne不存在该属性;
b) mappedBy标签一定是定义在the owned side(被拥有方的),他指向theowning side(拥有方);
c) 关系的拥有方负责关系的维护,在拥有方建立外键。所以用到@JoinColumn
d)mappedBy跟JoinColumn/JoinTable总是处于互斥的一方

这里的维护关联关系,拿多对多来说就是中间表,在不设置cascade的情况下,中间表由负责维护关联关系的一方维护

举例说明:

Game 和User 两个实体类,他们是多对多的关系,有中间表t_game-user.

在User中配置有:

@ManyToMany(mappedBy="users")
public List<Game> getGames() {
return games;
}

Game中配置有:

@ManyToMany
@JoinTable(name = "t_game_user",
joinColumns = {@JoinColumn(name = "game_id",referencedColumnName="gameId")},
inverseJoinColumns = {@JoinColumn(name = "user_id",referencedColumnName="id")})
public List<User> getUsers() {
  return users;
}

所以说由Game来维护他们的关联关系,即中间表。表现形式:
1.因为没有配置cascade所以分别给Game,User添加4条数据,然后手动在中间表中添加他们的关联关系
2.在程序中执行删除User
Hibernate: delete from t_user where id=?
Hibernate: delete from t_user where id=?
Hibernate: delete from t_user where id=?
Hibernate: delete from t_user where id=?
删除了User,并没有对中间表发生影响

在程序中执行删除Game
Hibernate:delete from t_game_user where game_id=?
Hibernate:delete from t_game_user where game_id=?
Hibernate:delete from t_game_user where game_id=?
Hibernate:delete from t_game_user where game_id=?
Hibernate:delete from t_game where game_id=?
Hibernate:delete from t_game where game_id=?
Hibernate:delete from t_game where game_id=?
Hibernate:delete from t_game where game_id=?
对中间表产生了影响,说明是Game在维护他们之间的关联关系