使用ManyToOne关系时,Hibernate user_roles表不会更新

时间:2018-06-13 13:48:07

标签: java spring hibernate jpa orm

我有3个表,User,Role和User_role。用户具有由" user"映射的OneToMany关系。使用CascadeType.Merge和user_role与cascadeTypes.All有2个ManyToOne关系,但是user_table在运行hibernate时永远不会填充数据。相反,值仅在用户和角色表中填充,但从不填充user_role表。

用户表定义

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="Id", nullable=false, updatable = false)
private Long id;

private String username;
private String password;
private String firstName;
private String lastName;

private String email;
private String phone;
private boolean enabled = true;

@OneToMany(mappedBy = "user", cascade=CascadeType.MERGE, fetch = 
FetchType.EAGER)
@JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();

UserRole表:

@Entity
@Table(name="user_role")
public class UserRole implements Serializable {
private static final long serialVersionUID = 890345L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long userRoleId;

@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL, 
optional=false)
@JoinColumn(name = "user_id")
private User user;

@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL,  
optional=false)
@JoinColumn(name = "role_id")
private Role role;

public UserRole () {}

public UserRole (User user, Role role) {
    this.user = user;
    this.role = role;
}

public long getUserRoleId() {
    return userRoleId;
}

public void setUserRoleId(long userRoleId) {
    this.userRoleId = userRoleId;
}

public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

public Role getRole() {
    return role;
}

public void setRole(Role role) {
    this.role = role;
}

}

调用从commandLine Runner调用的userServiceImpl中的userRepository.save()。

@Service

public class UserServiceImpl实现UserService {

private static final Logger LOG = LoggerFactory.getLogger(UserSecurityService.class);


@Autowired
private UserRepository userRepository;

@Autowired
private RoleRepository roleRepository;


// Indicates a  Database Transaction
@Transactional
public User createUser(User user, Set<UserRole> userRoles) {
    User localUser = userRepository.findByUsername(user.getUsername());

    if(localUser != null) {
        LOG.info("User with username {} already exist. Nothing will be done. ", user.getUsername());
    } else {


        for (UserRole ur : userRoles) {
            roleRepository.save(ur.getRole());
        }

        Set<UserRole> currentRoles =user.getUserRoles();

        currentRoles.addAll(userRoles);
        user.setUserRoles(currentRoles);


        localUser = userRepository.save(user);
    }

    return localUser;    
}

}

Main Class Run()

    public void run(String... args) throws Exception {
    User user1 = new User();
    user1.setFirstName("John");
    user1.setLastName("Adams");
    user1.setUsername("j");
    user1.setPassword(SecurityUtility.passwordEncoder().encode("p"));
    user1.setEmail("JAdams@gmail.com");
    Set<UserRole> userRoles = new HashSet<>();
    Role role1 = new Role();
    role1.setRoleId(1);
    role1.setName("ROLE_USER");
    userRoles.add(new UserRole(user1, role1));

    userService.createUser(user1, userRoles);
}

2 个答案:

答案 0 :(得分:0)

CascadeType.MERGE只会级联合并事件。持久性事件不会级联,因此如果您尝试保存新用户,则持久性事件将不会级联到User_role,并且不会将任何条目插入到user_role表中。

尝试添加CascadeType.PERSIST或更改为CascadeType.ALL,以便级联保存数据库中的记录。

@OneToMany(mappedBy = "user", cascade={CascadeType.MERGE, CascadeType.PERSIST}, fetch = FetchType.EAGER)

您可以在此答案中找到有关Cascade活动的更多信息:What do REFRESH and MERGE mean in terms of databases?

答案 1 :(得分:0)

我能够通过实现JPA实体管理器将数据持久化到user_role关联表。实例化了一个新的EntityManager类,并通过javax.persistence .merge()方法保存数据。