我正在使用 Spring Data、JPA 和 Hibernate 开发 Spring Web 应用程序。我正在测试一些东西,并注意到即使我删除了服务层中的保存语句,我的对象也会被保存。详细信息如下:
-----数据----
public interface FriendGroupRepository extends CrudRepository<FriendGroup, Long>, FriendGroupRepositoryCustom {
}
我的测试中没有使用 FriendGroupRepositoryCustom 中定义的方法。该测试仅涉及 CrudRepository 接口(interface)中的一种方法。
-----服务----
@Service
@Repository
@Transactional
public class AccountServiceImpl implements AccountService {
@Override
@Transactional
public void saveFriendGroup(FriendGroup group) {
friendGroupRepository.save(group);
}
}
删除friendGroupRepository.save(group);之后从上面可以看出,对象仍然被保存到数据库中。我进行了调试和跟踪,确认提交表单时确实调用了该方法。
------网络 Controller ---------
@RequestMapping(value={"/formtest"}, method=RequestMethod.POST)
public String formPost(HttpServletRequest request,
Model model, Map<String, Object> map,
@ModelAttribute("command") FriendGroup fg,
BindingResult result,
SessionStatus status ){
......
accountService.saveFriendGroup(fg);
.......
}
我很困惑,不知道出了什么问题。如果需要更多代码或配置,请告诉我。
感谢您的帮助! 问候。
最佳答案
这是一项功能,请参阅Hibernate documentation :
Transactional persistent instances (i.e. objects loaded, saved, created or queried by the Session) can be manipulated by the application, and any changes to persistent state will be persisted when the Session is flushed. This is discussed later in this chapter. There is no need to call a particular method (like update(), which has a different purpose) to make your modifications persistent.
Hibernate session 保留加载到其中的所有实体的缓存并跟踪它们的更改,当刷新 session 时,它会发出 SQL 更新以将这些更改保存到数据库中。因此,如果您的对象处于持久状态(您已在当前 session 中加载它),则对其进行的任何更改都将被持久化,而无需调用 save。
关于Spring数据、JPA和Hibernate : why does my object gets saved with the save statement removed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17681724/