Skip to content

Commit 702bcde

Browse files
committed
fixes mybatis#405 Changed the type of flushCache in @options from boolean to enum FlushCachePolicy.
1 parent ad96b80 commit 702bcde

File tree

9 files changed

+131
-7
lines changed

9 files changed

+131
-7
lines changed

src/main/java/org/apache/ibatis/annotations/Options.java

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,22 @@
2929
@Retention(RetentionPolicy.RUNTIME)
3030
@Target(ElementType.METHOD)
3131
public @interface Options {
32+
/**
33+
* The options for the {@link Options#flushCache()}.
34+
* The default is {@link FlushCachePolicy#DEFAULT}
35+
*/
36+
public enum FlushCachePolicy {
37+
/** <code>false</code> for select statement; <code>true</code> for insert/update/delete statement. */
38+
DEFAULT,
39+
/** Flushes cache regardless of the statement type. */
40+
TRUE,
41+
/** Does not flush cache regardless of the statement type. */
42+
FALSE
43+
}
44+
3245
boolean useCache() default true;
3346

34-
boolean flushCache() default false;
47+
FlushCachePolicy flushCache() default FlushCachePolicy.DEFAULT;
3548

3649
ResultSetType resultSetType() default ResultSetType.FORWARD_ONLY;
3750

src/main/java/org/apache/ibatis/builder/annotation/MapperAnnotationBuilder.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
import org.apache.ibatis.annotations.TypeDiscriminator;
5656
import org.apache.ibatis.annotations.Update;
5757
import org.apache.ibatis.annotations.UpdateProvider;
58+
import org.apache.ibatis.annotations.Options.FlushCachePolicy;
5859
import org.apache.ibatis.binding.BindingException;
5960
import org.apache.ibatis.binding.MapperMethod.ParamMap;
6061
import org.apache.ibatis.builder.BuilderException;
@@ -292,7 +293,11 @@ void parseStatement(Method method) {
292293
}
293294

294295
if (options != null) {
295-
flushCache = options.flushCache();
296+
if (FlushCachePolicy.TRUE.equals(options.flushCache())) {
297+
flushCache = true;
298+
} else if (FlushCachePolicy.FALSE.equals(options.flushCache())) {
299+
flushCache = false;
300+
}
296301
useCache = options.useCache();
297302
fetchSize = options.fetchSize() > -1 || options.fetchSize() == Integer.MIN_VALUE ? options.fetchSize() : null; //issue #348
298303
timeout = options.timeout() > -1 ? options.timeout() : null;

src/site/es/xdoc/java-api.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,7 @@ try (SqlSession session = sqlSessionFactory.openSession()) {
395395
<td><code>@Options</code></td>
396396
<td><code>Method</code></td>
397397
<td>Attributes of mapped statements.</td>
398-
<td>Esta anotación proporciona acceso a un gran conjunto de opciones de configuración que normalmente aparecen como atributos en los mapped statements. En lugar de complicar cada anotación existente la anotación Options proporciona una forma sencilla y concisa de acceder a estas opciones. Atributos: useCache=true, flushCache=false, resultSetType=FORWARD_ONLY, statementType=PREPARED, fetchSize=-1, timeout=-1, useGeneratedKeys=false, keyProperty=“id”, keyColumn=“”. Es importante comprender que las anotaciones en Java no permiten indicar un valor nulo. Por lo tanto, cuando usas la anotación Options el statement usará todos los valores por defecto. Presta atención a estos valores pro defecto para evitar comportamientos inesperados. La keyColumn solo se requiere para algunas bases de datos (como PostgreSQL) cuando la columna no es la primera columna de la tabla.</td>
398+
<td>Esta anotación proporciona acceso a un gran conjunto de opciones de configuración que normalmente aparecen como atributos en los mapped statements. En lugar de complicar cada anotación existente la anotación Options proporciona una forma sencilla y concisa de acceder a estas opciones. Atributos: useCache=true, flushCache=FlushCachePolicy.DEFAULT, resultSetType=FORWARD_ONLY, statementType=PREPARED, fetchSize=-1, timeout=-1, useGeneratedKeys=false, keyProperty=“id”, keyColumn=“”. Es importante comprender que las anotaciones en Java no permiten indicar un valor nulo. Por lo tanto, cuando usas la anotación Options el statement usará todos los valores por defecto. Presta atención a estos valores pro defecto para evitar comportamientos inesperados. La keyColumn solo se requiere para algunas bases de datos (como PostgreSQL) cuando la columna no es la primera columna de la tabla.</td>
399399
</tr>
400400
<tr>
401401
<td>

src/site/ja/xdoc/java-api.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,7 @@ try (SqlSession session = sqlSessionFactory.openSession()) {
409409
<td><code>Method</code></td>
410410
<td>マップドステートメントの属性</td>
411411
<td>このアノテーションを使うと、通常マップドステートメントの属性として指定される多様なスイッチや設定オプションにアクセスすることができます。<code>Options</code> アノテーションによって、各ステートメントのアノテーションを複雑化することなく、一貫したクリーンな方法で設定にアクセスできるよう工夫されています。キー: Attributes:
412-
<code>useCache=true</code>, <code>flushCache=false</code>, <code>resultSetType=FORWARD_ONLY</code>,
412+
<code>useCache=true</code>, <code>flushCache=FlushCachePolicy.DEFAULT</code>, <code>resultSetType=FORWARD_ONLY</code>,
413413
<code>statementType=PREPARED</code>, <code>fetchSize=-1</code>, <code>timeout=-1</code>,
414414
<code>useGeneratedKeys=false</code>, <code>keyProperty="id"</code>, <code>keyColumn=""</code>.
415415
Java アノテーションを使う場合、値として <code>null</code> を指定することはできないという制限があります。これはどういうことかというと、<code>Options</code> アノテーションを付加したステートメントにはデフォルトのオプションが適用されるということです。予期しない動作を防ぐため、各オプションのデフォルト値を把握しておくようにしてください。<br/><br/>

src/site/ko/xdoc/java-api.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -513,7 +513,7 @@ try (SqlSession session = sqlSessionFactory.openSession()) {
513513
<td>이 애노테이션은 매핑된 구문에 속성으로 존재하는 많은 분기(switch)와 설정 옵션에 접근할 수 있다.
514514
각 구문을 복잡하게 만들기 보다 Options 애노테이션으로 일관되고 깔끔한 방법으로 설정 할수 있게 한다.
515515
사용가능한 속성들 : useCache=true,
516-
flushCache=false,
516+
flushCache=FlushCachePolicy.DEFAULT,
517517
resultSetType=FORWARD_ONLY,
518518
statementType=PREPARED,
519519
fetchSize=-1,

src/site/xdoc/java-api.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ try (SqlSession session = sqlSessionFactory.openSession()) {
430430
<td>This annotation provides access to the wide range of switches and configuration options that are normally
431431
present on the mapped statement as attributes. Rather than complicate each statement annotation, the
432432
<code>Options</code> annotation provides a consistent and clear way to access these. Attributes:
433-
<code>useCache=true</code>, <code>flushCache=false</code>, <code>resultSetType=FORWARD_ONLY</code>,
433+
<code>useCache=true</code>, <code>flushCache=FlushCachePolicy.DEFAULT</code>, <code>resultSetType=FORWARD_ONLY</code>,
434434
<code>statementType=PREPARED</code>, <code>fetchSize=-1</code>, <code>timeout=-1</code>,
435435
<code>useGeneratedKeys=false</code>, <code>keyProperty="id"</code>, <code>keyColumn=""</code>.
436436
It's important to understand that with Java Annotations, there is no way to specify <code>null</code> as a value.

src/site/zh/xdoc/java-api.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -670,7 +670,7 @@ select,是映射语句(也就是映射器方
670670
而不是将每条语句注解变复
671671
杂,Options 注解提供连贯清晰的方式
672672
来访问它们。属性:useCache=true ,
673-
flushCache=false
673+
flushCache=FlushCachePolicy.DEFAULT
674674
,
675675
resultSetType=FORWARD_ONLY ,
676676
statementType=PREPARED ,

src/test/java/org/apache/ibatis/submitted/cache/CacheTest.java

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,4 +168,96 @@ public void testplan3() {
168168
}
169169
}
170170

171+
/*-
172+
* Test case for #405
173+
*
174+
* Test Plan with Autocommit on:
175+
* 1) SqlSession 1 executes "select * from A".
176+
* 2) SqlSession 1 closes.
177+
* 3) SqlSession 2 executes "insert into person (id, firstname, lastname) values (3, hello, world)"
178+
* 4) SqlSession 2 closes.
179+
* 5) SqlSession 3 executes "select * from A".
180+
* 6) SqlSession 3 closes.
181+
*
182+
* Assert:
183+
* Step 5 returns 3 row.
184+
*/
185+
@Test
186+
public void shouldInsertWithOptionsFlushesCache() {
187+
SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
188+
try {
189+
PersonMapper pm = sqlSession1.getMapper(PersonMapper.class);
190+
Assert.assertEquals(2, pm.findAll().size());
191+
} finally {
192+
sqlSession1.close();
193+
}
194+
195+
SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
196+
try {
197+
PersonMapper pm = sqlSession2.getMapper(PersonMapper.class);
198+
Person p = new Person(3, "hello", "world");
199+
pm.createWithOptions(p);
200+
} finally {
201+
sqlSession2.close();
202+
}
203+
204+
SqlSession sqlSession3 = sqlSessionFactory.openSession(true);
205+
try {
206+
PersonMapper pm = sqlSession3.getMapper(PersonMapper.class);
207+
Assert.assertEquals(3, pm.findAll().size());
208+
} finally {
209+
sqlSession3.close();
210+
}
211+
}
212+
213+
/*-
214+
* Test Plan with Autocommit on:
215+
* 1) SqlSession 1 executes select to cache result
216+
* 2) SqlSession 1 closes.
217+
* 3) SqlSession 2 executes insert without flushing cache
218+
* 4) SqlSession 2 closes.
219+
* 5) SqlSession 3 executes select (flushCache = false)
220+
* 6) SqlSession 3 closes.
221+
* 7) SqlSession 4 executes select (flushCache = true)
222+
* 8) SqlSession 4 closes.
223+
*
224+
* Assert:
225+
* Step 5 returns 2 row.
226+
* Step 7 returns 3 row.
227+
*/
228+
@Test
229+
public void shouldApplyFlushCacheOptions() {
230+
SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
231+
try {
232+
PersonMapper pm = sqlSession1.getMapper(PersonMapper.class);
233+
Assert.assertEquals(2, pm.findAll().size());
234+
} finally {
235+
sqlSession1.close();
236+
}
237+
238+
SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
239+
try {
240+
PersonMapper pm = sqlSession2.getMapper(PersonMapper.class);
241+
Person p = new Person(3, "hello", "world");
242+
pm.createWithoutFlushCache(p);
243+
} finally {
244+
sqlSession2.close();
245+
}
246+
247+
SqlSession sqlSession3 = sqlSessionFactory.openSession(true);
248+
try {
249+
PersonMapper pm = sqlSession3.getMapper(PersonMapper.class);
250+
Assert.assertEquals(2, pm.findAll().size());
251+
} finally {
252+
sqlSession3.close();
253+
}
254+
255+
SqlSession sqlSession4 = sqlSessionFactory.openSession(true);
256+
try {
257+
PersonMapper pm = sqlSession4.getMapper(PersonMapper.class);
258+
Assert.assertEquals(3, pm.findWithFlushCache().size());
259+
} finally {
260+
sqlSession4.close();
261+
}
262+
}
171263
}

src/test/java/org/apache/ibatis/submitted/cache/PersonMapper.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
import org.apache.ibatis.annotations.CacheNamespace;
2121
import org.apache.ibatis.annotations.Delete;
2222
import org.apache.ibatis.annotations.Insert;
23+
import org.apache.ibatis.annotations.Options;
24+
import org.apache.ibatis.annotations.Options.FlushCachePolicy;
2325
import org.apache.ibatis.annotations.Select;
2426

2527
@CacheNamespace
@@ -28,9 +30,21 @@ public interface PersonMapper {
2830
@Insert("insert into person (id, firstname, lastname) values (#{id}, #{firstname}, #{lastname})")
2931
public void create(Person person);
3032

33+
@Insert("insert into person (id, firstname, lastname) values (#{id}, #{firstname}, #{lastname})")
34+
@Options
35+
public void createWithOptions(Person person);
36+
37+
@Insert("insert into person (id, firstname, lastname) values (#{id}, #{firstname}, #{lastname})")
38+
@Options(flushCache = FlushCachePolicy.FALSE)
39+
public void createWithoutFlushCache(Person person);
40+
3141
@Delete("delete from person where id = #{id}")
3242
public void delete(int id);
3343

3444
@Select("select id, firstname, lastname from person")
3545
public List<Person> findAll();
46+
47+
@Select("select id, firstname, lastname from person")
48+
@Options(flushCache = FlushCachePolicy.TRUE)
49+
public List<Person> findWithFlushCache();
3650
}

0 commit comments

Comments
 (0)