【发布时间】:2017-01-25 02:33:26
【问题描述】:
使用 Java 和 Spring,我有一个已修改但尚未持久化的实体。我想将它与它的原始状态进行比较,即数据库中仍然存在的状态。但是,当我为实体进行获取以获取旧状态时,它总是返回处于 modified 状态的实体。
为了更好地说明这一点,下面显示了一个示例。
-
MyEntity类表示实体。 -
MyEntityRepository类是一个Spring Data Repository,用于为MyEntity实体执行数据库交互。 -
MyService类有一个称为save的事务方法,它将新版本的MyEntity(称为entity)与oldEntity进行比较。如果entity和oldEntity不同,则将entity存入数据库;否则不保存。
oldEntity 从存储库中获取并与entity 进行比较。但是,完成此操作后,oldEntity始终与 entity 相同。 (entity 中的更改值反映在oldEntity 中。)
由于entity 尚未保存,我如何获取实体的状态,因为它当前存在于数据库中而不是当前上下文中?是否可以使用 Spring 注释或设置传播值以超出当前持久性上下文以获取实体,以便它是真实的持久值,而不是当前上下文中的值?
@Service
public class MyService {
@Autowire
private MyEntityRepository repository;
@Transactional
public boolean save(MyEntity entity) {
MyEntity oldEntity = repository.findOne(entity.getId());
if (entity.compareTo(oldEntity) != 0) {
repository.save(entity);
}
}
}
public interface MyEntityRepository extends PagingAndSortingRepository<MyEntity, Long> {
MyEntity findByName(String name);
}
@Entity
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
@Column(nullable = false)
protected String name;
public Long getId() { ... }
public void setId(Long id) { ... }
public String getName() { ... }
public void setName(String name) { ... }
public int compareTo(MyEntity entity) { ... }
}
【问题讨论】:
-
这样做的用例是什么?
-
根据您的提供程序,当即将执行的查询依赖于当前持久性上下文中的新实体或更新实体时,可能会发生刷新。这解释了您所看到的 - 您的提供程序刷新待处理的更改以确保即将发出的查询的一致性。 O
-
@MarkOfHall 当且仅当多个实体属性之一发生更改时,我的特定用例才会调用附加处理。因此,我想获取保存的实体状态并将其与修改后的实体状态进行比较。
标签: java spring spring-data spring-data-jpa