【问题标题】:How to insert only in join table but not in reference table in JPA Hibernate如何在 JPA Hibernate 中仅在连接表中插入而不在参考表中插入
【发布时间】:2023-03-27 15:44:01
【问题描述】:

我有两个实体 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 中执行此操作时,将创建以下表:accountuser_rolerole

因为我的角色数量是固定的。我手动插入了它们

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;
    }

【问题讨论】:

  • 您的“在帐户表中插入新条目”代码可能很有用。我认为您正在尝试通过将其角色设置为 new Role() 而不是首先从 db 获取角色来插入新用户。
  • "我尝试在帐户表中插入一个新条目"... 怎么样?你有什么代码可以分享给我们吗?
  • 添加了 @KamilNoster 并插入和更新了一段代码
  • @lealceldeiro 添加代码
  • @stallion 我不确定您是如何尝试更新帐户的。 accountDto在这里的作用是什么?它应该带来必须设置为account 的角色还是只是一个从数据库中获取的数据访问对象,某种存储库?

标签: java mysql spring hibernate jpa


【解决方案1】:

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

【讨论】:

  • 我得到了这个异常:原因:org.hibernate.PersistentObjectException:分离的实体传递给持久化:com.techjava.springbootsecuritymysql.model.Role
猜你喜欢
  • 1970-01-01
  • 2016-08-17
  • 1970-01-01
  • 2014-08-09
  • 1970-01-01
  • 2011-03-19
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
相关资源
最近更新 更多