更新不在Hibernate中工作多对多关系表

时间:2017-07-26 05:21:19

标签: java spring hibernate jpa

我正在尝试设计一个CRUD控制器,这里插入和删除操作工作正常,但更新不起作用。提交更新时,只更新用户表,但不更新角色表。

User.java

@Entity
@Table(name="users")
public class User implements UserDetails {
    @Id
    @GeneratedValue (strategy = GenerationType.AUTO)
    private Long id;

    @Column(length = 128, nullable = false)
    private String firstName; 

    @Column(length = 128, unique = true, nullable = false)
    private String email;                       // required; unique

    @Column(unique = true, nullable = false, length=128)
    private String name;

    @Column(length = 128, nullable = false)
    private String password;                    // required

    @Column
    private boolean enabled;

    @JsonBackReference
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(
            name = "company_user",
            joinColumns = @JoinColumn(name = "userId"),
            inverseJoinColumns = @JoinColumn(name = "companyId")
    )
    private Set<Company> companies = new HashSet<Company>();

    @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE})
    @JoinTable(
            name = "user_role",
            joinColumns = @JoinColumn(name = "userId", referencedColumnName="id"),
            inverseJoinColumns = @JoinColumn(name = "roleId", referencedColumnName="id")
    )
    private Set<Role> roles = new HashSet<Role>();

Role.java

@Entity
public class Role extends BaseObject {
    @Column(length = 64)
    private String description;

UserController.java

@PostMapping("/saveUser")
        public void save(@ModelAttribute User user, BindingResult bindingResult, HttpServletRequest req, HttpServletResponse rsp) throws IOException {

            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        //  LOGGER.info("--------------role User ID----------" + user.getRoles());
            user.setRoles(user.getRoles());
            userService.registerUser(user);

            req.setAttribute("users", userService.findAllUsers());
            req.setAttribute("mode", "USER_VIEW");
            rsp.sendRedirect("showUser");
        }


**UserService.Java**


public User registerUser(User user) {
        Optional<User> exists = userRepository.findOneByName(user.getName());
        return exists.isPresent() ? userRepository.save(exists.get().merge(user))
                : userRepository.save(user);
    }

我怎样才能克服这种情况?请帮帮我......

1 个答案:

答案 0 :(得分:1)

尝试在此字段上使用 cascade = CascadeType.ALL
    私人设置角色=新HashSet();

我假设您的isPresent返回false并且UserRepository.save(用户)正在运行,这将只保存用户而不是角色,因为您正在使用 cascade = {CascadeType.MERGE} 它可能会解决您的问题。