首页 > 解决方案 > 如何在 JPA Hibernate 中仅在连接表中插入而不在参考表中插入

问题描述

我有两个实体UserRole. 一个用户可以有多个角色,每个角色可以与多个用户相关联。即,用户角色具有多对多关系

例如:用户RamRobJohn是管理员

我正在用户和角色之间创建一个连接表来存储信息。

@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表中插入一个新条目...我只想将其插入accountuser_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;
    }

标签: javamysqlspringhibernatejpa

解决方案


尝试在 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/


推荐阅读