如何执行原生SQL更新不触发JPA @PreUpdate避免lastUpdateDate修改
前置修正
你提供的Account类代码存在明显笔误,先修正避免字段取值混乱:
// 原错误写法 public String getLastUpdateDate() { return m_indexDate; } // 修正后 public Date getLastUpdateDate() { return m_lastUpdateDate; }
解决方案
以下方案均可实现仅更新indexDate、不触发@PreUpdate回调修改lastUpdateDate的需求,可根据业务场景选择:
方案1:使用@Modifying注解的直接更新语句(推荐)
直接在Repository层定义字段更新的JPQL/原生SQL,绕开实体生命周期,完全不会触发@PreUpdate回调:
public interface AccountRepository extends JpaRepository<Account, String> { @Modifying @Transactional // 也可以加在业务层方法上 @Query(nativeQuery = true, value = "update account set index_date = :indexDate where id = :accountId") int updateIndexDateById(@Param("indexDate") Date indexDate, @Param("accountId") String accountId); }
- 必须添加
@Modifying注解标识该语句为写操作 - 若持久化上下文存在对应Account实体缓存,可配置
@Modifying(clearAutomatically = true)自动清空缓存,避免后续查询拿到旧数据
方案2:新增临时开关控制@PreUpdate逻辑
在Account类中新增非持久化的开关字段,灵活控制是否跳过lastUpdateDate更新:
class Account { // 原有字段保持不变 @Transient private boolean skipLastUpdate = false; @PreUpdate void preUpdate() { if (!skipLastUpdate) { setLastUpdateDate(new Date()); } } // 补充skipLastUpdate的getter、setter方法 }
使用时仅需在更新indexDate前打开开关即可:
Account account = accountRepository.findById(accountId).orElseThrow(); account.setIndexDate(new Date()); account.setSkipLastUpdate(true); accountRepository.save(account);
该方案适合需要同时操作实体其他字段、仅需跳过lastUpdateDate更新的场景。
方案3:使用CriteriaUpdate程序式更新
通过JPA Criteria API直接执行字段级更新,同样不会加载实体、不触发生命周期回调:
@Autowired EntityManager entityManager; @Transactional public void updateAccountIndexDate(String accountId, Date newIndexDate) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaUpdate<Account> update = cb.createCriteriaUpdate(Account.class); Root<Account> root = update.from(Account.class); update.set(root.get("m_indexDate"), newIndexDate); update.where(cb.equal(root.get("m_id"), accountId)); entityManager.createQuery(update).executeUpdate(); }
内容的提问来源于stack exchange,提问作者Borgy Manotoy
相关产品推荐
相关产品推荐

