Skip to content

Commit

Permalink
fixes #405 Changed the type of flushCache in @options from boolean to…
Browse files Browse the repository at this point in the history
… enum FlushCachePolicy.
  • Loading branch information
harawata committed Jan 27, 2016
1 parent 4f7af77 commit 283d91e
Show file tree
Hide file tree
Showing 9 changed files with 131 additions and 7 deletions.
15 changes: 14 additions & 1 deletion src/main/java/org/apache/ibatis/annotations/Options.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,22 @@
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Options {
/**
* The options for the {@link Options#flushCache()}.
* The default is {@link FlushCachePolicy#DEFAULT}
*/
public enum FlushCachePolicy {
/** <code>false</code> for select statement; <code>true</code> for insert/update/delete statement. */
DEFAULT,
/** Flushes cache regardless of the statement type. */
TRUE,
/** Does not flush cache regardless of the statement type. */
FALSE
}

boolean useCache() default true;

boolean flushCache() default false;
FlushCachePolicy flushCache() default FlushCachePolicy.DEFAULT;

ResultSetType resultSetType() default ResultSetType.FORWARD_ONLY;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
import org.apache.ibatis.annotations.TypeDiscriminator;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.annotations.Options.FlushCachePolicy;
import org.apache.ibatis.binding.BindingException;
import org.apache.ibatis.binding.MapperMethod.ParamMap;
import org.apache.ibatis.builder.BuilderException;
Expand Down Expand Up @@ -292,7 +293,11 @@ void parseStatement(Method method) {
}

if (options != null) {
flushCache = options.flushCache();
if (FlushCachePolicy.TRUE.equals(options.flushCache())) {
flushCache = true;
} else if (FlushCachePolicy.FALSE.equals(options.flushCache())) {
flushCache = false;
}
useCache = options.useCache();
fetchSize = options.fetchSize() > -1 || options.fetchSize() == Integer.MIN_VALUE ? options.fetchSize() : null; //issue #348
timeout = options.timeout() > -1 ? options.timeout() : null;
Expand Down
2 changes: 1 addition & 1 deletion src/site/es/xdoc/java-api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ try (SqlSession session = sqlSessionFactory.openSession()) {
<td><code>@Options</code></td>
<td><code>Method</code></td>
<td>Attributes of mapped statements.</td>
<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>
<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>
</tr>
<tr>
<td>
Expand Down
2 changes: 1 addition & 1 deletion src/site/ja/xdoc/java-api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ try (SqlSession session = sqlSessionFactory.openSession()) {
<td><code>Method</code></td>
<td>マップドステートメントの属性</td>
<td>このアノテーションを使うと、通常マップドステートメントの属性として指定される多様なスイッチや設定オプションにアクセスすることができます。<code>Options</code> アノテーションによって、各ステートメントのアノテーションを複雑化することなく、一貫したクリーンな方法で設定にアクセスできるよう工夫されています。キー: Attributes:
<code>useCache=true</code>, <code>flushCache=false</code>, <code>resultSetType=FORWARD_ONLY</code>,
<code>useCache=true</code>, <code>flushCache=FlushCachePolicy.DEFAULT</code>, <code>resultSetType=FORWARD_ONLY</code>,
<code>statementType=PREPARED</code>, <code>fetchSize=-1</code>, <code>timeout=-1</code>,
<code>useGeneratedKeys=false</code>, <code>keyProperty="id"</code>, <code>keyColumn=""</code>.
Java アノテーションを使う場合、値として <code>null</code> を指定することはできないという制限があります。これはどういうことかというと、<code>Options</code> アノテーションを付加したステートメントにはデフォルトのオプションが適用されるということです。予期しない動作を防ぐため、各オプションのデフォルト値を把握しておくようにしてください。<br/><br/>
Expand Down
2 changes: 1 addition & 1 deletion src/site/ko/xdoc/java-api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,7 @@ try (SqlSession session = sqlSessionFactory.openSession()) {
<td>이 애노테이션은 매핑된 구문에 속성으로 존재하는 많은 분기(switch)와 설정 옵션에 접근할 수 있다.
각 구문을 복잡하게 만들기 보다 Options 애노테이션으로 일관되고 깔끔한 방법으로 설정 할수 있게 한다.
사용가능한 속성들 : useCache=true,
flushCache=false,
flushCache=FlushCachePolicy.DEFAULT,
resultSetType=FORWARD_ONLY,
statementType=PREPARED,
fetchSize=-1,
Expand Down
2 changes: 1 addition & 1 deletion src/site/xdoc/java-api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ try (SqlSession session = sqlSessionFactory.openSession()) {
<td>This annotation provides access to the wide range of switches and configuration options that are normally
present on the mapped statement as attributes. Rather than complicate each statement annotation, the
<code>Options</code> annotation provides a consistent and clear way to access these. Attributes:
<code>useCache=true</code>, <code>flushCache=false</code>, <code>resultSetType=FORWARD_ONLY</code>,
<code>useCache=true</code>, <code>flushCache=FlushCachePolicy.DEFAULT</code>, <code>resultSetType=FORWARD_ONLY</code>,
<code>statementType=PREPARED</code>, <code>fetchSize=-1</code>, <code>timeout=-1</code>,
<code>useGeneratedKeys=false</code>, <code>keyProperty="id"</code>, <code>keyColumn=""</code>.
It's important to understand that with Java Annotations, there is no way to specify <code>null</code> as a value.
Expand Down
2 changes: 1 addition & 1 deletion src/site/zh/xdoc/java-api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -670,7 +670,7 @@ select,是映射语句(也就是映射器方
而不是将每条语句注解变复
杂,Options 注解提供连贯清晰的方式
来访问它们。属性:useCache=true ,
flushCache=false
flushCache=FlushCachePolicy.DEFAULT
,
resultSetType=FORWARD_ONLY ,
statementType=PREPARED ,
Expand Down
92 changes: 92 additions & 0 deletions src/test/java/org/apache/ibatis/submitted/cache/CacheTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -168,4 +168,96 @@ public void testplan3() {
}
}

/*-
* Test case for #405
*
* Test Plan with Autocommit on:
* 1) SqlSession 1 executes "select * from A".
* 2) SqlSession 1 closes.
* 3) SqlSession 2 executes "insert into person (id, firstname, lastname) values (3, hello, world)"
* 4) SqlSession 2 closes.
* 5) SqlSession 3 executes "select * from A".
* 6) SqlSession 3 closes.
*
* Assert:
* Step 5 returns 3 row.
*/
@Test
public void shouldInsertWithOptionsFlushesCache() {
SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
try {
PersonMapper pm = sqlSession1.getMapper(PersonMapper.class);
Assert.assertEquals(2, pm.findAll().size());
} finally {
sqlSession1.close();
}

SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
try {
PersonMapper pm = sqlSession2.getMapper(PersonMapper.class);
Person p = new Person(3, "hello", "world");
pm.createWithOptions(p);
} finally {
sqlSession2.close();
}

SqlSession sqlSession3 = sqlSessionFactory.openSession(true);
try {
PersonMapper pm = sqlSession3.getMapper(PersonMapper.class);
Assert.assertEquals(3, pm.findAll().size());
} finally {
sqlSession3.close();
}
}

/*-
* Test Plan with Autocommit on:
* 1) SqlSession 1 executes select to cache result
* 2) SqlSession 1 closes.
* 3) SqlSession 2 executes insert without flushing cache
* 4) SqlSession 2 closes.
* 5) SqlSession 3 executes select (flushCache = false)
* 6) SqlSession 3 closes.
* 7) SqlSession 4 executes select (flushCache = true)
* 8) SqlSession 4 closes.
*
* Assert:
* Step 5 returns 2 row.
* Step 7 returns 3 row.
*/
@Test
public void shouldApplyFlushCacheOptions() {
SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
try {
PersonMapper pm = sqlSession1.getMapper(PersonMapper.class);
Assert.assertEquals(2, pm.findAll().size());
} finally {
sqlSession1.close();
}

SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
try {
PersonMapper pm = sqlSession2.getMapper(PersonMapper.class);
Person p = new Person(3, "hello", "world");
pm.createWithoutFlushCache(p);
} finally {
sqlSession2.close();
}

SqlSession sqlSession3 = sqlSessionFactory.openSession(true);
try {
PersonMapper pm = sqlSession3.getMapper(PersonMapper.class);
Assert.assertEquals(2, pm.findAll().size());
} finally {
sqlSession3.close();
}

SqlSession sqlSession4 = sqlSessionFactory.openSession(true);
try {
PersonMapper pm = sqlSession4.getMapper(PersonMapper.class);
Assert.assertEquals(3, pm.findWithFlushCache().size());
} finally {
sqlSession4.close();
}
}
}
14 changes: 14 additions & 0 deletions src/test/java/org/apache/ibatis/submitted/cache/PersonMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Options.FlushCachePolicy;
import org.apache.ibatis.annotations.Select;

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

@Insert("insert into person (id, firstname, lastname) values (#{id}, #{firstname}, #{lastname})")
@Options
public void createWithOptions(Person person);

@Insert("insert into person (id, firstname, lastname) values (#{id}, #{firstname}, #{lastname})")
@Options(flushCache = FlushCachePolicy.FALSE)
public void createWithoutFlushCache(Person person);

@Delete("delete from person where id = #{id}")
public void delete(int id);

@Select("select id, firstname, lastname from person")
public List<Person> findAll();

@Select("select id, firstname, lastname from person")
@Options(flushCache = FlushCachePolicy.TRUE)
public List<Person> findWithFlushCache();
}

0 comments on commit 283d91e

Please sign in to comment.