【发布时间】:2019-01-23 02:22:14
【问题描述】:
我有一个基本的 SpringBoot 应用程序。使用 Spring Initializer、JPA、嵌入式 Tomcat、Thymeleaf 模板引擎和打包为可执行 JAR 文件我有这个实体: 我有一个公司的用户实体
@Entity
@Table(name="t_user")
public class User implements Serializable, UserDetails {
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Company company;
}
我创建了一个公司,我保存它,然后,我将它附加到用户:
user.setCompany(companyService.findAll().iterator().next());
但是当我保存用户时,我得到了这个错误:
detached entity passed to persist: com.elcor.backend.persistence.domain.backend.Company
这里是服务层的createUser方法
@Transactional
public User createUser(User user, Set<UserRole> userRoles) {
User localUser = userRepository.findByEmail(user.getEmail());
if (localUser != null) {
LOG.info("User with username {} and email {} already exist. Nothing will be done. ",
user.getUsername(), user.getEmail());
} else {
String encryptedPassword = passwordEncoder.encode(user.getPassword());
user.setPassword(encryptedPassword);
//Plan plan = new Plan(plansEnum);
// It makes sure the plans exist in the database
//if (!planRepository.exists(plansEnum.getId())) {
// plan = planRepository.save(plan);
//}
//user.setPlan(plan);
for (UserRole ur : userRoles) {
roleRepository.save(ur.getRole());
}
user.getUserRoles().addAll(userRoles);
localUser = userRepository.save(user);
}
return localUser;
}
【问题讨论】:
-
这个电话
companyService.findAll().iterator().next()会给你一个id为的公司吗? -
是的,它返回一个带有 id 的公司
-
可以在保存用户的地方添加语句吗?
标签: hibernate spring-mvc spring-boot spring-data-jpa spring-data