可能有些人也有過類似需求,一般都會選擇使用其他的方式如Spring-JDBC等方式解決。
能否通過MyBatis實現這樣的功能呢?
為了讓通用Mapper更徹底的支持多表操作以及更靈活的操作,在2.2.0版本增加了一個可以直接執行SQL的新類SqlMapper。
我們來了解一下SqlMapper。
SqlMapper提供的方法
SqlMapper提供了以下這些公共方法:
一共14個方法,這些方法的命名和參數和SqlSession接口的很像,只是基本上第一個參數都成了sql。
其中Object value為入參,入參形式和SqlSession中的入參一樣,帶有入參的方法,在使用時sql可以包含#{param}或${param}形式的參數,這些參數需要通過入參來傳值。需要的參數過多的時候,參數可以使用Map類型。另外這種情況下的sql還支持下面這種復雜形式:
String sql = "<script>select * from sys_user where 1=1" + "<if test=/"usertype != null/">usertype = #{usertype}</if></script>";
這種情況用的比較少,不多說。
不帶有Object value的所有方法,sql中如果有參數需要手動拼接成一個可以直接執行的sql語句。
在selectXXX方法中,使用Class<T> resultType可以指定返回類型,否則就是Map<String,Object>類型。
實例化SqlMapper
SqlMapper構造參數public SqlMapper(SqlSession sqlSession),需要一個入參SqlSession sqlSession,在一般系統中,可以按照下面的方式獲取:
SqlSession sqlSession = (...);//通過某些方法獲取sqlSession//創建sqlMapperSqlMapper sqlMapper = new SqlMapper(sqlSession);
如果使用的Spring,那么可以按照下面的方式配置<bean>:
<bean id="sqlMapper" class="com.github.abel533.sql.SqlMapper" scope="prototype"> <constructor-arg ref="sqlSession"/></bean>
在Service中使用的時候可以直接使用@Autowired注入。
簡單例子
在src/test/java目錄的com.github.abel533.sql包中包含這些方法的測試。
下面挑幾個看看如何使用。
selectList
//查詢,返回List<Map>List<Map<String, Object>> list = sqlMapper.selectList("select * from country where id < 11");//查詢,返回指定的實體類List<Country> countryList = sqlMapper.selectList("select * from country where id < 11", Country.class);//查詢,帶參數countryList = sqlMapper.selectList("select * from country where id < #{id}", 11, Country.class);//復雜點的查詢,這里參數和上面不同的地方,在于傳入了一個對象Country country = new Country();country.setId(11);countryList = sqlMapper.selectList("<script>" + "select * from country " + " <where>" + " <if test=/"id != null/">" + " id < #{id}" + " </if>" + " </where>" + "</script>", country, Country.class);
selectOne
Map<String, Object> map = sqlMapper.selectOne("select * from country where id = 35");map = sqlMapper.selectOne("select * from country where id = #{id}", 35);Country country = sqlMapper.selectOne("select * from country where id = 35", Country.class);country = sqlMapper.selectOne("select * from country where id = #{id}", 35, Country.class);
insert,update,delete
//insertint result = sqlMapper.insert("insert into country values(1921,'天朝','TC')");Country tc = new Country();tc.setId(1921);tc.setCountryname("天朝");tc.setCountrycode("TC");//注意這里的countrycode和countryname故意寫反的result = sqlMapper.insert("insert into country values(#{id},#{countrycode},#{countryname})" , tc);//updateresult = sqlMapper.update("update country set countryname = '天朝' where id = 35");tc = new Country();tc.setId(35);tc.setCountryname("天朝");int result = sqlMapper.update("update country set countryname = #{countryname}" + " where id in(select id from country where countryname like 'A%')", tc);//deleteresult = sqlMapper.delete("delete from country where id = 35");result = sqlMapper.delete("delete from country where id = #{id}", 35);
注意
通過上面這些例子應該能對此有個基本的了解,但是如果你使用參數方式,建議閱讀下面的文章:
深入了解MyBatis參數
實現原理
最初想要設計這個功能的時候,感覺會很復雜,想的也復雜,需要很多個類,因此當時沒有實現。
突發奇想,設計了現在的這種方式。并且有種強烈的感覺就是幸好昨天沒有嘗試去實現,因為昨天晚上思考這個問題的時候是晚上10點多,而今天晚上7點開始思考。我很慶幸在一個更清醒的狀態下去寫這段代碼。
下面簡單說思路和實現方式。
在寫MyBatis分頁插件的時候熟悉了MappedStatement類。
在寫通用Mapper的時候熟悉了xml轉SqlNode結構。
如果我根據SQL動態的創建一個MappedStatement,然后使用MappedStatement的id在sqlSession中執行不就可以了嗎?
想到這一點,一切就簡單了。
看看下面select查詢創建MappedStatement的代碼:
/** * 創建一個查詢的MS * @param msId * @param sqlSource 執行的sqlSource * @param resultType 返回的結果類型 */private void newSelectMappedStatement(String msId, SqlSource sqlSource, final Class<?> resultType) { MappedStatement ms = new MappedStatement.Builder( configuration, msId, sqlSource, SqlCommandType.SELECT) .resultMaps(new ArrayList<ResultMap>() { { add(new ResultMap.Builder(configuration, "defaultResultMap", resultType, new ArrayList<ResultMapping>(0)).build()); } }) .build(); //緩存 configuration.addMappedStatement(ms);}
代碼是不是很簡單,這段代碼的關鍵是參數sqlSource,下面是創建SqlSource的方法,分為兩種。
一種是一個完整的sql,不需要參數的,可以直接執行的:
StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);
其中configuration從sqlSession中獲取,sql就是用戶傳入到sql語句,是不是也很簡單?
另一種是支持動態sql的,支持參數的SqlSource:
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);
是不是也很簡單?這個方法其實可以兼容上面的StaticSqlSource,這里比上面多了一個parameterType,因為這兒是可以傳遞參數的,另外languageDriver是從configuration中獲取的。
是不是很簡單?
我一開始也沒想到MyBatis直接執行sql實現起來會這么的容易。
insert,delete,update方法的創建更容易,因為他們的返回值都是int,所以處理起來更簡單,有興趣的可以查看SqlMapper的源碼。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答
圖片精選