Spring数据、JPA和Hibernate : why does my object gets saved with the save statement removed?

标签 spring hibernate jpa

我正在使用 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/

相关文章:

java - 如何使用 Bluemix Liberty 运行时将 EntityManager 注入(inject) EJB 中?

java - 使用组合键映射 JPA 实体

java - 通过 Spring-boot、Spring-data、Hibernate 保存 @ManyToOne 实体后,重复的键值违反了唯一约束 "b_name_key"

java - 如何在Thymeleaf `sec:authorize`属性中使用Spring EL表达式

spring - 单例和 @Autowired 返回 NULL

java - 如何为 Spring Boot 应用程序设置 org.hibernate.org.hibernate.FlushMode?

java - 条件查询返回[]

java - 当 @Transactional 注解中指定回滚已检查异常时,Spring 是否会回滚运行时异常

java - 为什么 Spring 登录表单不会显示登录失败的任何错误信息?

hibernate - 参数值 [....] 与预期类型不匹配 [java.util.Collection (n/a)]