1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.submitted.raw_sql_source;
17
18 import java.io.Reader;
19
20 import org.apache.ibatis.BaseDataTest;
21 import org.apache.ibatis.io.Resources;
22 import org.apache.ibatis.mapping.SqlSource;
23 import org.apache.ibatis.scripting.defaults.RawSqlSource;
24 import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
25 import org.apache.ibatis.session.SqlSession;
26 import org.apache.ibatis.session.SqlSessionFactory;
27 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
28 import org.junit.jupiter.api.Assertions;
29 import org.junit.jupiter.api.BeforeAll;
30 import org.junit.jupiter.api.Test;
31
32 class RawSqlSourceTest {
33
34 private static SqlSessionFactory sqlSessionFactory;
35
36 @BeforeAll
37 static void setUp() throws Exception {
38
39 try (Reader reader = Resources
40 .getResourceAsReader("org/apache/ibatis/submitted/raw_sql_source/mybatis-config.xml")) {
41 sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
42 }
43
44
45 BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(),
46 "org/apache/ibatis/submitted/raw_sql_source/CreateDB.sql");
47 }
48
49 @Test
50 void shouldUseRawSqlSourceForAnStaticStatement() {
51 test("getUser1", RawSqlSource.class);
52 }
53
54 @Test
55 void shouldUseDynamicSqlSourceForAnStatementWithInlineArguments() {
56 test("getUser2", DynamicSqlSource.class);
57 }
58
59 @Test
60 void shouldUseDynamicSqlSourceForAnStatementWithXmlTags() {
61 test("getUser3", DynamicSqlSource.class);
62 }
63
64 private void test(String statement, Class<? extends SqlSource> sqlSource) {
65 try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
66 Assertions.assertEquals(sqlSource,
67 sqlSession.getConfiguration().getMappedStatement(statement).getSqlSource().getClass());
68 String sql = sqlSession.getConfiguration().getMappedStatement(statement).getSqlSource().getBoundSql('?').getSql();
69 Assertions.assertEquals("select * from users where id = ?", sql);
70 User user = sqlSession.selectOne(statement, 1);
71 Assertions.assertEquals("User1", user.getName());
72 }
73 }
74
75 }