【问题标题】:Spring Data, JPA, and Hibernate: why does my object gets saved with the save statement removed?Spring Data、JPA 和 Hibernate:为什么我的对象在保存语句被删除的情况下被保存?
【发布时间】:2013-07-14 22:33:20
【问题描述】:

我正在使用 Spring Data、JPA 和 Hibernate 做一个 Spring Web 应用程序。我正在测试一些东西,并注意到即使我删除了服务层中的保存语句,我的对象也被保存了。以下是详细信息:

-----数据----

public interface FriendGroupRepository extends CrudRepository<FriendGroup, Long>, FriendGroupRepositoryCustom {
}

FriendGroupRepositoryCustom 中定义的方法在我的测试中没有使用。该测试仅涉及 CrudRepository 接口中的一种方法。

-----服务----

@Service
@Repository
@Transactional
public class AccountServiceImpl implements AccountService  {

@Override
@Transactional
public void saveFriendGroup(FriendGroup group) {
    friendGroupRepository.save(group);
}

}

在我删除了friendGroupRepository.save(group);之后从上面,对象仍然被保存到数据库中。我进行了调试和跟踪,并确认在我提交表单时确实调用了此方法。

------ 网络控制器 ---------

@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);     
    .......
}

我很困惑,不知道出了什么问题。如果需要更多代码或配置,请告诉我。

感谢您的帮助! 问候。

【问题讨论】:

    标签: spring hibernate jpa


    【解决方案1】:

    这是一个功能,见Hibernate documentation

    事务性持久实例(即加载、保存的对象, 由 Session 创建或查询)可以由 应用程序,并且对持久状态的任何更改都将被持久化 当 Session 被刷新时。这将在本章后面讨论。 无需调用特定方法(如 update(),它具有 不同的目的)使您的修改持久化。

    Hibernate 会话保留所有加载到其中的实体的缓存并跟踪对它们的更改,当刷新会话时,它会发出 SQL 更新以将这些更改持久保存到数据库中。因此,如果您的对象处于持久状态(您已在当前会话中加载它),则对其进行的任何更改都将保持不变,而无需调用 save。

    【讨论】:

    • 内森,非常感谢您的意见。所以保存对象不需要调用friendGroupRepository.save(group),对吗?
    • @curious1: 对,只要在同一个 Hibernate 会话中加载对象即可。
    猜你喜欢
    • 2018-10-26
    • 2014-03-31
    • 1970-01-01
    • 2017-08-31
    • 2013-04-21
    • 2021-05-31
    • 2015-05-10
    • 1970-01-01
    • 2021-11-21
    相关资源
    最近更新 更多