1. 程式人生 > >mybatis通用mapper的方法解析

mybatis通用mapper的方法解析

Mapper的內建方法
model層就是實體類,對應資料庫的表。controller層是Servlet,主要是負責業務模組流程的控制,呼叫service介面的方法,在struts2就是Action。Service層主要做邏輯判斷,Dao層是資料訪問層,與資料庫進行對接。至於Mapper是mybtis框架的對映用到,mapper對映檔案在dao層用。

下面是介紹一下Mapper的內建方法:

1、countByExample ===>根據條件查詢數量

?
1 2 3 4 5 6 7 int countByExample(UserExample example); //下面是一個完整的案列
UserExample example = new UserExample(); Criteria criteria = example.createCriteria(); criteria.andUsernameEqualTo("joe"); int count = userDAO.countByExample(example);

 相當於:select count(*) from user where username='joe'
 
2、deleteByExample ===>根據條件刪除多條

?
1 2 3 4 5 6 7 8 int deleteByExample(AccountExample example);
//下面是一個完整的案例 UserExample example = new UserExample(); Criteria criteria = example.createCriteria(); criteria.andUsernameEqualTo("joe"); userDAO.deleteByExample(example); 相當於:delete from user where username='joe'

3、deleteByPrimaryKey===>根據條件刪除單條

?
1 2 int deleteByPrimaryKey(Integer id);
userDAO.deleteByPrimaryKey(101);

相當於:

?
1 2 delete from user where id=101

4、insert===>插入資料

?
1 2 3 4 5 6 7 8 9 int insert(Account record); //下面是完整的案例 User user = new User(); //user.setId(101); user.setUsername("test"); user.setPassword("123456") user.setEmail("[email protected]"); userDAO.insert(user);

 相當於:

?
1 insert into user(ID,username,password,email) values(101,'test','123456','[email protected]');

 5、insertSelective===>插入資料

?
1 int insertSelective(Account record);

6、selectByExample===>根據條件查詢資料

?
1 2 3 4 5 6 7 8 9 10 11 12 List<Account> selectByExample(AccountExample example); //下面是一個完整的案例 UserExample example = new UserExample(); Criteria criteria = example.createCriteria(); criteria.andUsernameEqualTo("joe"); criteria.andUsernameIsNull(); example.setOrderByClause("username asc,email desc"); List<?>list = userDAO.selectByExample(example); 相當於:select * from user where username = 'joe' and username is null order by username asc,email desc //注:在iBator 生成的檔案UserExample.java中包含一個static 的內部類 Criteria ,在Criteria中有很多方法,主要是定義SQL 語句where後的查詢條件。

 7、selectByPrimaryKey===>根據主鍵查詢資料

?
1 Account selectByPrimaryKey(Integer id);//相當於select * from user where id = 變數id

 
8、updateByExampleSelective===>按條件更新值不為null的欄位

?
1 2 3 4 5 6 7 8 9 10 int updateByExampleSelective(@Param("record") Account record, @Param("example") AccountExample example); //下面是一個完整的案列 UserExample example = new UserExample(); Criteria criteria = example.createCriteria(); criteria.andUsernameEqualTo("joe"); User user = new User(); user.setPassword("123"); userDAO.updateByPrimaryKeySelective(user,example); 相當於:update user set password='123' where username='joe'

 
9、updateByExampleSelective===>按條件更新

?
1 int updateByExample(@Param("record") Account record, @Param("example") AccountExample example);

10、updateByPrimaryKeySelective===>按條件更新

?
1 2 3 4 5 6 7 8 int updateByPrimaryKeySelective(Account record); //下面是一個完整的案例 User user = new User(); user.setId(101); user.setPassword("joe"); userDAO.updateByPrimaryKeySelective(user);

相當於:

?
1 update user set password='joe' where id=101
?
1 2 3 4 5 6 7 8 int updateByPrimaryKeySelective(Account record); //下面是一個完整的案例 User user = new User(); user.setId(101); user.setPassword("joe"); userDAO.updateByPrimaryKeySelective(user);

相當於:update user set password='joe' where id=101

11、updateByPrimaryKey===>按主鍵更新

?
1 2 3 4 5 6 7 8 9 int updateByPrimaryKey(Account record); //下面是一個完整的案例 User user =new User(); user.setId(101); user.setUsername("joe"); user.setPassword("joe"); user.setEmail("[email protected]"); userDAO.updateByPrimaryKey(user);

 相當於:

?
1 update user set username='joe',password='joe',email='[email protected]' where id=101
?
1 2 3 4 5 6 7 8 9 int updateByPrimaryKey(Account record); //下面是一個完整的案例 User user =new User(); user.setId(101); user.setUsername("joe"); user.setPassword("joe"); user.setEmail("[email protected]"); userDAO.updateByPrimaryKey(user);

 相當於:

?
1 update user set username='joe',password='joe',email='[email protected]' where id=101

 
解析mapper的xml配置檔案
我們來看看mybatis是怎麼讀取mapper的xml配置檔案並解析其中的sql語句。

我們還記得是這樣配置sqlSessionFactory的:

?
1 2 3 4 5 6 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">   <property name="dataSource" ref="dataSource" />  <property name="configLocation" value="classpath:configuration.xml"></property>   <property name="mapperLocations" value="classpath:com/xxx/mybatis/mapper/*.xml"/>   <property name="typeAliasesPackage" value="com.tiantian.mybatis.model" />   </bean

這裡配置了一個mapperLocations屬性,它是一個表示式,sqlSessionFactory會根據這個表示式讀取包com.xxx.mybaits.mapper下面的所有xml格式檔案,那麼具體是怎麼根據這個屬性來讀取配置檔案的呢?

答案就在SqlSessionFactoryBean類中的buildSqlSessionFactory方法中:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 if (!isEmpty(this.mapperLocations)) { for (Resource mapperLocation : this.mapperLocations) { if (mapperLocation == null) { continue; } try { XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), configuration, mapperLocation.toString(), configuration.getSqlFragments()); xmlMapperBuilder.parse(); } catch (Exception e) { throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e); } finally { ErrorContext.instance().reset(); } if (logger.isDebugEnabled()) { logger.debug("Parsed mapper file: '" + mapperLocation + "'"); } } }

mybatis使用XMLMapperBuilder類的例項來解析mapper配置檔案。

?
1 2 3 4 5 6 7 8 9 10 11 12 public XMLMapperBuilder(Reader reader, Configuration configuration, String resource, Map<String, XNode> sqlFragments) { this(new XPathParser(reader, true, configuration.getVariables(), new XMLMapperEntityResolver()), configuration, resource, sqlFragments); } private XMLMapperBuilder(XPathParser parser, Configuration configuration, String resource, Map<String, XNode> sqlFragments) { super(configuration); this.builderAssistant = new MapperBuilderAssistant(configuration, resource); this.parser = parser; this.sqlFragments = sqlFragments; this.resource = resource; }

接著系統呼叫xmlMapperBuilder的parse方法解析mapper。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public void parse() { //如果configuration物件還沒載入xml配置檔案(避免重複載入,實際上是確認是否解析了mapper節點的屬性及內容, //為解析它的子節點如cache、sql、select、resultMap、parameterMap等做準備), //則從輸入流中解析mapper節點,然後再將resource的狀態置為已載入 if (!configuration.isResourceLoaded(resource)) { configurationElement(parser.evalNode("/mapper")); configuration.addLoadedResource(resource); bindMapperForNamespace(); } //解析在configurationElement函式中處理resultMap時其extends屬性指向的父物件還沒被處理的<resultMap>節點 parsePendingResultMaps(); //解析在configurationElement函式中處理cache-ref時其指向的物件不存在的<cache>節點(如果cache-ref先於其指向的cache節點載入就會出現這種情況) parsePendingChacheRefs(); //同上,如果cache沒載入的話處理statement時也會丟擲異常 parsePendingStatements(); }

mybatis解析mapper的xml檔案的過程已經很明顯了,接下來我們看看它是怎麼解析mapper的:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 private void configurationElement(XNode context) { try { //獲取mapper節點的namespace屬性 String namespace = context.getStringAttribute("namespace"); if (namespace.equals("")) { throw new BuilderException("Mapper's namespace cannot be empty"); } //設定當前namespace builderAssistant.setCurrentNamespace(namespace); //解析mapper的<cache-ref>節點 cacheRefElement(context.evalNode("cache-ref")); //解析mapper的<cache>節點 cacheElement(context.evalNode("cache")); //解析mapper的<parameterMap>節點 parameterMapElement(context.evalNodes("/mapper/parameterMap")); //解析mapper的<resultMap>節點 resultMapElements(context.evalNodes("/mapper/resultMap")); //解析mapper的<sql>節點 sqlElement(context.evalNodes("/mapper/sql")); //使用XMLStatementBuilder的物件解析mapper的<select>、<insert>、<update>、<delete>節點, //mybaits會使用MappedStatement.Builder類build一個MappedStatement物件, //所以mybaits中一個sql對應一個MappedStatement buildStatementFromContext(context.evalNodes("select|insert|update|delete")); } catch (Exception e) { throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e); } }

configurationElement函式幾乎解析了mapper節點下所有子節點,至此mybaits解析了mapper中的所有節點,並將其加入到了Configuration物件中提供給sqlSessionFactory物件隨時使用。這裡我們需要補充講一下mybaits是怎麼使用XMLStatementBuilder類的物件的parseStatementNode函數借用MapperBuilderAssistant類物件builderAssistant的addMappedStatement解析MappedStatement並將其關聯到Configuration類物件的:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 public void parseStatementNode() { //ID屬性 String id = context.getStringAttribute("id"); //databaseId屬性 String databaseId = context.getStringAttribute("databaseId"); if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) { return; } //fetchSize屬性 Integer fetchSize = context.getIntAttribute("fetchSize"); //timeout屬性 Integer timeout = context.getIntAttribute("timeout"); //parameterMap屬性 String parameterMap = context.getStringAttribute("parameterMap"); //parameterType屬性 String parameterType = context.getStringAttribute("parameterType"); Class<?> parameterTypeClass = resolveClass(parameterType); //resultMap屬性 String resultMap = context.getStringAttribute("resultMap"); //resultType屬性 String resultType = context.getStringAttribute("resultType"); //lang屬性 String lang = context.getStringAttribute("lang"); LanguageDriver langDriver = getLanguageDriver(lang); Class<?> resultTypeClass = resolveClass(resultType); //resultSetType屬性 String resultSetType = context.getStringAttribute("resultSetType"); StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString())); ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType); String nodeName = context.getNode().getNodeName(); SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH)); //是否是<select>節點 boolean isSelect = sqlCommandType == SqlCommandType.SELECT; //flushCache屬性 boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect); //useCache屬性 boolean useCache = context.getBooleanAttribute("useCache", isSelect); //resultOrdered屬性 boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false); // Include Fragments before parsing XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant); includeParser.applyIncludes(context.getNode()); // Parse selectKey after includes and remove them. processSelectKeyNodes(id, parameterTypeClass, langDriver); // Parse the SQL (pre: <selectKey> and <include> were parsed and removed) SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass); //resultSets屬性 String resultSets = context.getStringAttribute("resultSets"); //keyProperty屬性 String keyProperty = context.getStringAttribute("keyProperty"); //keyColumn屬性 String keyColumn = context.getStringAttribute("keyColumn"); KeyGenerator keyGenerator; String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX; keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true); if (configuration.hasKeyGenerator(keyStatementId)) { keyGenerator = configuration.getKeyGenerator(keyStatementId); } else { //useGeneratedKeys屬性 keyGenerator = context.getBooleanAttribute("useGeneratedKeys", configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType)) ? new Jdbc3KeyGenerator() : new NoKeyGenerator(); } builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass, resultSetTypeEnum, flushCache, useCache, resultOrdered,  keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets); }
由以上程式碼可以看出mybaits使用XPath解析mapper的配置檔案後將其中的resultMap、parameterMap、cache、statement等節點使用關聯的builder建立並將得到的物件關聯到configuration物件中,而這個configuration物件可以從sqlSession中獲取的,這就解釋了我們在使用sqlSession對資料庫進行操作時mybaits怎麼獲取到mapper並執行其中的sql語句的問題。

相關推薦

mybatis通用mapper原始碼解析(二)

1.javabean的屬性值生成sql /** * 獲取所有查詢列,如id,name,code... * * @param entityClass * @return */ public static String getAllColumns(C

mybatis通用mapper方法解析

Mapper的內建方法model層就是實體類,對應資料庫的表。controller層是Servlet,主要是負責業務模組流程的控制,呼叫service介面的方法,在struts2就是Action。Service層主要做邏輯判斷,Dao層是資料訪問層,與資料庫進行對接。至於M

mybatis通用mapper源碼解析(二)

bool emp nts content new type() als append column 1.javabean的屬性值生成sql /** * 獲取所有查詢列,如id,name,code... * * @param entityC

Mybatis通用Mapper使用方法說明, 裡面有開源的原始碼地址(to 李琳老師)

Mybatis通用Mapper 極其方便的使用Mybatis單表的增刪改查 優點? 不客氣的說,使用這個通用Mapper甚至能改變你對Mybatis單表基礎操作不方便的想法,使用它你能簡單的使用單表的增刪改查,包含動態的增刪改查. 程式使用攔截器實現具

Mybatis通用mapper之insertList方法

記錄一個通用mapper的一個小坑,MySQLMapper的insertList方法中傳入list時,這個Entity的主鍵必須為自增主鍵,否則他在執行sql是不會去插入主鍵,自然就會報一些奇怪的錯誤了,比如DB2的-407

淺談Mybatis通用Mapper使用方法

對單表進行增刪改查是專案中不可避免的需求,Mybatis的通用Mapper外掛使這些操作變得簡單新增maven依賴在對應工程的pom.xml檔案中新增<dependency> <groupId>javax.persistence</groupId> <

Mybatis通用Mapper

mybatis 選擇 pla all 必須 fork bean code 長度 極其方便的使用Mybatis單表的增刪改查 項目地址:http://git.oschina.net/free/Mapper 優點? 不客氣的說,使用這個通用Mapper甚至

Mybatis通用Mapper(轉)

transient 項目 同時 你在 但是 擁有 32位 sele spa 轉自:http://blog.csdn.net/isea533/article/details/41457529 極其方便的使用Mybatis單表的增刪改查 項目地址:http://git.

mybatis通用mapper動態查詢表名

module turn 返回值 實體類 public 實體 bsp 實現接口 class 1:給個@Table註解,給個默認的表名,不寫也可以,但是要駝峰轉下劃線匹配 @Table(name = "conf_default") 2:添加非表字段參數,用於接受動態

mybatis通用mapper的Example查詢

    mybatis的通用mapper,多用於單表查詢,介面內部為我們提供了單表查詢的基礎查詢語法,可以極大地幫助我們簡化程式設計。 接下來讓我們動手試一試: 我建的是springboot專案: 先導依賴: <dependency> <

Mybatis通用Mapper的使用

一、前言 使用Mybatis的開發者,大多數都會遇到一個問題,就是要寫大量的SQL在xml檔案中,除了特殊的業務邏輯SQL之外,還有大量結構類似的增刪改查SQL。而且,當資料庫表結構改動時,對應的所有SQL以及實體類都需要更改。這工作量和效率的影響或許就是區別增刪改查程式設計師和真正程式

SSM專案使用Mybatis通用mapper外掛tk.mybatis的用法

Mybatis 與 Hibernate的一個很大的區別就是Mybatis所有的資料庫操作語句都需要自己寫,對於簡單的單表操作來說是比較煩瑣的。因此有人就開發了tk.mybatis外掛,通過這個外掛,你可以省略許多簡單的單表資料庫操作語句而直接呼叫相對應的dao方

spring boot整合mybatis通用mapper實現Druid多資料來源

      在以前的專案中用springMVC加原生的mybatis框架使用過多資料來源的配置,是用xml配置的。在這次的新專案裡面使用到了tk的通用mapper,剛好專案結束,利用空閒時間寫了個全註解的多資料來源配置小demo

springboot 配置mybatis通用mapper

宣告: 此處為springboot 配置mybatis的通用mapper方 一共步其他多餘操作不要有 1新增mapper依賴 一定要有以下依賴的jar包 注意jar包版本,太高會導致功能不可用 <!-- Spring Boot Mybatis 依賴 --&

MyBatis通用Mapper與分頁PageHelper混淆報錯問題

背景 當同時引入通用Mapper與PageHelper兩款外掛的時候,會存在報錯的可能。 如果像這樣,先執行通用Mapper,再執行分頁外掛就會出錯 <!-- 通用Mapper外掛 -->

Spring boot 整合mybatis通用mapper配置步驟及注意事項

一、新增依賴 二、繼承通用mapper,可以重寫和選擇需要的mapper方法,可以去掉一些不需要的方法(一般直接繼承即可) Mapper3提供的全部的方法,可以檢視Mapper3通用介面大全 三、application.properties配置 四、設定dao路徑 在

SpringBoot整合Mybatis-通用mapper使用二級快取

未使用二級快取前測試 執行了三條sql: 開啟二級快取 在yml檔案中: 在Mapper介面上使用@CacheNamespace註解: 資料庫entity需要序列化: 測試: 執行結果: 發現只執行了一條sql,後面兩條sql會

整合springboot+mvc+mybatis(通用mapper)+druid+jsp+bootstrap實現許可權管理檔案上傳下載多資料來源切換操作日誌記錄等功能

花了兩週,學習了下springboot,然後做個小東西練練手.專案基於jdk1.8+maven整合了springboot+mvc+mybatis(通用mapper)+druid+jsp+bootstrap等技術,springboot+Listener(監聽器),Filter

Mybatis通用Mapper介紹與使用

前言使用Mybatis的開發者,大多數都會遇到一個問題,就是要寫大量的SQL在xml檔案中,除了特殊的業務邏輯SQL之外,還有大量結構類似的增刪改查SQL。而且,當資料庫表結構改動時,對應的所有SQL以及實體類都需要更改。這工作量和效率的影響或許就是區別增刪改查程式設計師和真

Mybatis通用Mapper(springboot環境下使用)

1、新增pom檔案依賴 <!--mapper --> <dependency> <groupId>tk.mybatis</groupId>