在我的Spring项目中,我分别有域和模型层。域层只是实体,映射到MySQL db中的表。模型用于服务层。我有两个表:User和Roles,它们具有ManyToMany关系。
proxy_buffering off;
proxy_buffer_size 4k;
proxy_request_buffering off;
proxy_cache off;
underscores_in_headers on;
模型
@Entity
@Table(name = "user")
public class UserEntity {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToMany(mappedBy="users", cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private List<RoleEntity> roles;
//..Getters Setters
}
@Entity
@Table(name = "role")
public class RoleEntity {
@Id
@GeneratedValue
private Long id;
private String value;
@ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@JoinTable(name = "user_role",
joinColumns = @JoinColumn(name = "role_id") , inverseJoinColumns = @JoinColumn(name = "user_id") )
private List<UserEntity> users;
}
存储库层
public class User {
private Long id;
private String name;
private List<Role> roles;
}
public class Role {
private Long id;
private String value;
private List<User> users;
}
服务
@Repository
public interface UserRepo extends JpaRepository<UserEntity, Long>{
}
问题是 - 每次我检索用户,并更新它的属性(例如名称),然后将其保存到表中,连接表user_role中的行也会覆盖。例如,如果它是
id = 1,user_id = 1,role_id = 1
,比更新后变为
id = 2,user_id = 1,role_id = 1
。
@Service
public class UserService {
@Autowired
private UserRepo userRepo;
MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
MapperFacade mapper = mapperFactory.getMapperFacade();
public void save(User user) {
userRepo.save(mapper.map(user, UserEntity.class));
}
public User getUser(Long id) {
return mapper.map(userRepo.findOne(id), User.class);
}
}
没有mapper就可以正常工作,所以mapper就是原因。我无法解决任何问题。有没有人遇到同样的问题?感谢任何帮助。