[英]Hibernate oneToMany - object references an unsaved transient instance
[英]Hibernate “object references an unsaved transient instance”
我的User
在ManyToOne
關系中處於Organisation
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;
使用新的組織工作創建用戶但是當我輸入現有的用戶時,我得到以下內容:
分離的實體傳遞給持久化
根據我的理解,這是一個雙向一致性問題,但到目前為止答案對我沒有幫助。
最后這是我的實體類:
@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
}
我解決了我的問題,
正如您在上面的映射器中看到的,我正在創建一個新的OrganisatonEntity
實例,無論它是什么,即使它已經存在!
所以我的代碼中的一個小變化解決了它:
public UserEntity map(UserInfo userInfo, OrganisationEntity organisationEntity);
代替
public UserEntity map(UserInfo userInfo, Long orgaId);
當組織已經存在時,我會將其分配給我的UserEntity
如下所示:
user.setOrganisation(organisationEntity);
而不是實例化一個新對象。
問題解決了 !
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.