程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java的MyBatis框架中Mapper映照設置裝備擺設的應用及道理解析

Java的MyBatis框架中Mapper映照設置裝備擺設的應用及道理解析

編輯:關於JAVA

Java的MyBatis框架中Mapper映照設置裝備擺設的應用及道理解析。本站提示廣大學習愛好者:(Java的MyBatis框架中Mapper映照設置裝備擺設的應用及道理解析)文章只能為提供參考,不一定能成為您想要的結果。以下是Java的MyBatis框架中Mapper映照設置裝備擺設的應用及道理解析正文


Mapper的內置辦法
model層就是實體類,對應數據庫的表。controller層是Servlet,重要是擔任營業模塊流程的掌握,挪用service接口的辦法,在struts2就是Action。Service層重要做邏輯斷定,Dao層是數據拜訪層,與數據庫停止對接。至於Mapper是mybtis框架的映照用到,mapper映照文件在dao層用。

上面是引見一下Mapper的內置辦法:

1、countByExample ===>依據前提查詢數目

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 ===>依據前提刪除多條

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===>依據前提刪除單條

int deleteByPrimaryKey(Integer id);
userDAO.deleteByPrimaryKey(101); 

相當於:

delete from user where id=101
 

4、insert===>拔出數據

int insert(Account record);
 
//上面是完全的案例
User user = new User();
 //user.setId(101);
 user.setUsername("test");
 user.setPassword("123456")
 user.setEmail("[email protected]");
 userDAO.insert(user);

 相當於:

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

 5、insertSelective===>拔出數據

int insertSelective(Account record);

6、selectByExample===>依據前提查詢數據

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===>依據主鍵查詢數據

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

 
8、updateByExampleSelective===>按前提更新值不為null的字段

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===>按前提更新

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

10、updateByPrimaryKeySelective===>按前提更新

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
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===>按主鍵更新

int updateByPrimaryKey(Account record);

//上面是一個完全的案例
User user =new User();
 user.setId(101);
 user.setUsername("joe");
 user.setPassword("joe");
 user.setEmail("[email protected]");
 userDAO.updateByPrimaryKey(user);

 相當於:

update user set username='joe',password='joe',email='[email protected]' where id=101
int updateByPrimaryKey(Account record);
 
//上面是一個完全的案例
User user =new User();
 user.setId(101);
 user.setUsername("joe");
 user.setPassword("joe");
 user.setEmail("[email protected]");
 userDAO.updateByPrimaryKey(user);

 相當於:

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

 
解析mapper的xml設置裝備擺設文件
我們來看看mybatis是怎樣讀取mapper的xml設置裝備擺設文件並解析個中的sql語句。

我們還記得是如許設置裝備擺設sqlSessionFactory的:

<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辦法中:

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設置裝備擺設文件。

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。

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的:

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類對象的:

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語句的成績。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved