java - 如何在 JPA Hibernate 中仅在连接表中插入而不在参考表中插入
问题描述
我有两个实体User
和Role
. 一个用户可以有多个角色,每个角色可以与多个用户相关联。即,用户角色具有多对多关系
例如:用户Ram、Rob和John是管理员
我正在用户和角色之间创建一个连接表来存储信息。
@Entity
@Table(name = "account")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private int id;
@Column(unique = true)
private String username;
@Transient
@JsonIgnore
private String password;
@ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
@Column
private boolean deleted;
}
和 Role.java
@Entity
@Table(name = "role")
@Data
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="role_id")
private int id;
@Column(name="role",unique=true)
private String role;
}
在 Spring Boot 中执行此操作时,将创建以下表:account
, user_role
, role
.
因为我的角色数量是固定的。我手动插入它们
INSERT INTO `role` VALUES (1,'ADMIN');
INSERT INTO `role` VALUES (2,'USER');
现在从我的 java spring boot 应用程序中,我尝试在帐户表中插入一个新条目。也尝试在Role
表中插入一个新条目...我只想将其插入account
和user_role
表中,而不是role
表中...
谁能让我知道该怎么做?
更新:
这是帐户插入部分(创建帐户代码)
//创建账户
public Account createAccount(AccountDto account) {
Account newAccount = new Account();
newAccount.setPassword(account.getPassword());
newAccount.setUsername(account.getUsername());
Set<Role> roles = new HashSet<Role>();
Role role = new Role();
role.setRole(account.getRole());
roles.add(role);
newAccount.setRoles(roles);
Account savedAccount = save(newAccount);
return savedAccount;
}
//更新账户
public Account updateAccount(String oldUserName, AccountDto accountDto) {
Account account = accountRepository.findByUsername(oldUserName);
if (account != null) {
Set<Role> roleset = new HashSet<Role>();
if(accountDto.getRole() != null && !accountDto.getRole().isEmpty()){
Role role = roleRepository.findByRole(accountDto.getRole());
if (role == null) {
roleset.add(role);
}
}
account.setRoles(roleset);
account.setUsername(accountDto.getUsername());
account = accountRepository.save(account);
return account;
} else
return null;
}
解决方案
尝试在 Account 类中编译 CascadeType。
@ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.)
您还需要为帐户实体添加链接。
@ManyToMany(fetch = FetchType.EAGER,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "role")
private Set<Account> accounts = new Set<Account>();
你可以在这里找到很好的教程https://www.callicoder.com/hibernate-spring-boot-jpa-many-to-many-mapping-example/
推荐阅读
- opencart - OpenCart 3 更改货币(总是返回美元)
- mysql - 编写一个 sql 查询以获取具有多个值的记录
- docker - docker compose 上的 Falco 安全性和 falcosidekick
- graphql - Apollo GraphQL 动态认证子图
- html - 带有搜索值的属性类型中的 Eclipse 警告
- git - git rebase,手动解决所有冲突
- python - 允许用户直接从 Python 中的 URL 中选择网页元素
- html - 为什么当我输入 nodejs 正在侦听的浏览器 IP 和端口时看不到响应?
- html - 如何在表单html中居中输入按钮
- vue.js - Vue Composition API:安装回设置中的初始化变量