【发布时间】:2017-04-27 09:51:08
【问题描述】:
我的Users 在Organisations 中处于ManyToOne 关系中,当使用现有组织创建用户时,我试图将其分配给它而不创建新组织。
在我的服务中,我是这样创建用户的:
@Override
public UserInfo createUser(UserInfo newUser) {
// Check if organisation exists
OrganisationEntity orga = organisationDao.findByName(newUser.getOrganisation());
if (orga != null) {
// Organisation exists, we save it with the correct ID
return mapper.map(userDao.save(mapper.map(newUser, orga.getId())));
} else {
// Organisation does NOT exists, we save it and create a new one
return mapper.map(userDao.save(mapper.map(newUser, (long) -1)));
}
}
我的Mapper(帮助我将模型转换为实体)是:
public UserEntity map(UserInfo userInfo, Long orgaId) {
UserEntity user = new UserEntity();
user.setEmail(userInfo.getEmail());
user.setFirstName(userInfo.getFirstName());
user.setLastName(userInfo.getLastName());
user.setPassword(userInfo.getPassword());
OrganisationEntity orga = new OrganisationEntity();
orga.setName(userInfo.getOrganisation());
// We set the organisation's ID
if (orgaId != -1)
orga.setId(orgaId);
user.setOrganisation(orga);
return user;
}
这是我的UserDao:
@Transactional
public interface UserDao extends CrudRepository<UserEntity, Long> {
UserEntity save(UserEntity user);
}
最后是我UserEntity 中的关系:
@ManyToOne(targetEntity = OrganisationEntity.class, cascade = CascadeType.ALL)
@JoinColumn(name = "orga_id")
private OrganisationEntity organisation;
使用新的组织工作创建用户,但是当我输入现有用户时,我得到以下信息:
传递给持久化的分离实体
在我的understanding 看来,这是一个双向一致性问题,但到目前为止答案对我没有帮助。
最后是我的实体类:
@Entity
@Table(name = "\"user\"")
public class UserEntity {
@Id
@Column(name = "user_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private String email;
@NotNull
private String firstName;
@NotNull
private String lastName;
@NotNull
private String password;
@ManyToOne(targetEntity = OrganisationEntity.class, cascade = CascadeType.ALL)
@JoinColumn(name = "orga_id")
private OrganisationEntity organisation;
// Getters & Setters
}
和
@Entity
@Table(name = "organisation")
public class OrganisationEntity {
@Id
@Column(name = "orga_id", unique = true)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Column(unique = true)
private String name;
// Getters & Setters
}
【问题讨论】:
-
为什么不让hibernate为你做映射呢?您可以在类上使用注释并插入使用
session.save();方法。无需自己实现。 -
能否请您开发一个答案?对我来说不是很清楚。
-
您的课程的邮政编码。然后我可以创建一个答案
-
我已经发布了我的实体类。