1、代码示例
@Modifying(clearAutomatically = true)
@Query(value = "update customer_adviser set " +
" auditStatus = ?1, "+
" optUserCode = ?3,"+
" optUserName = ?4 "+
" where id = ?2", nativeQuery = true)
int updateCustomerAdviserStatusByID(int auditResult,Long id, String optUserCode, String optUserName);
2、详解
点击@Modifying,进入这个注解(源码,已经贴在文章后面),我们能看到,它是指可以清除底层持久化上下文,即entityManager这个类;Jpa底层实现会有一级缓存,也就是在更新完数据库后,如果后面去用这个对象,你再去查这个对象,这个对象是在一级缓存,但是并没有跟数据库同步,此时使用clearAutomatically=true,就会刷新Hibernate的一级缓存, 否则在同一接口中,更新一个对象,接着查询这个对象,那么查出来的这个对象还是之前的没有更新前的状态。
Defines whether we should clear the underlying persistence context after executing the modifying query.
翻译:
定义在执行修改查询后是否应该清除底层持久化上下文。
/*
* Copyright 2008-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.jpa.repository;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates a method should be regarded as modifying query.
*
* @author Oliver Gierke
* @author Christoph Strobl
* @author Nicolas Cirigliano
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Documented
public @interface Modifying {
/**
* Defines whether we should flush the underlying persistence context before executing the modifying query.
*
* @return
*/
boolean flushAutomatically() default false;
/**
* Defines whether we should clear the underlying persistence context after executing the modifying query.
*
* @return
*/
boolean clearAutomatically() default false;
}