我在使用Hibernate時遇到了問題。我有以下方法:
@Override
public Task assignedUser(Long taskId, Long userId) {
final Task taskBeforeUpdate = taskRepository.findById(taskId) 。
if (Objects.isNull(taskBeforeUpdate)) {
throw new TaskNotFoundException("Canot assign, taskId "未找到任務")。)
}
if (!Objects.isNull(taskBeforeUpdate.getUser() )) {
throw new BadRequestException("用戶不能分配到id為" taskId "的任務上,因為任務已經有了用戶")。)
}
final User user = userRepository.findById(userId)。
final Task assignedTask = taskRepository.assignUser(taskBeforeUpdate.getId(),user.getId())。
kafkaSenderTaskProducer.sendUpdatedEvent(assignedTask,taskBeforeUpdate)。
return assignedTask。
這個方法應該將用戶分配到任務上,并通過TaskBeforeUpdate和TaskAfterUpdate向kafka消費者發送訊息。但我有個問題,當我試圖分配用戶時,我的BeforeUpdateTask把他的所有欄位都改為TaskAfterUpdate。這并不奏效,但我不知道為什么他要改變所有的值。
public Task assignUser(long taskId, Long userId) {
log.debug("AssignUser.E with Task id: {} and User id: {}", taskId, userId) 。
try {
tx.begin()。
Task task = entityManager.find(Task.class, taskId)。
User user = entityManager.find(User.class, userId)。
task.setUser(user)。
final Task updatedTask = entityManager.merge(task)。
tx.commit()。
if (Objects.isNull(upedTask)) {
log.warning("AssignUser.X with null"/span>)。
return null。
}
log.debug("AssignUser.X with Task: {}"/span>, updatedTask)。
return updatedTask;
} catch (final HibernateException ex) {
tx.rollback()。
throw new TaskDAOException("Canot crate user", ex) 。
}
@Override
public Task findById(Long id) throws TaskDAOException {
log.debug("FindById.E with Task id: {}", id)。
tx.begin()。
final Task task = entityManager.find(Task.class, id)。
tx.commit()。
if (Objects.isNull(task)) {
log.warning("FindById.X with null"/span>)。
return null;
}
log.debug("FindById.X with Task: {}"/span>, task)。
return task。
}
uj5u.com熱心網友回復:
EntityManger管理著所有附加的Entity。一個物體通過它的ID是唯一的。所以基本上,如果你用它的ID加載一個物體兩次,你會得到相同的物件。不僅僅是一個相等的物件,它真的是相同的。
你可以在taskRepository.assignUser之前從物體管理器中洗掉taskBeforeUpdate,這應該可以解決這個問題
。entityManager.detach(taskBeforeUpdate)。
或者我將把taskBeforeUpdate物件映射到另一個不同類別的物件中,然后傳遞給kafkaSenderTaskProducer.sendUpdatedEvent(資料傳輸物件)
。轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/307774.html
標籤:
