Java的MyBatis框架中Mapper映射配置的使用及原理解析
Mapper的内置方法
model层就是实体类,对应数据库的表。controller层是Servlet,主要是负责业务模块流程的控制,调用service接口的方法,在struts2就是Action。Service层主要做逻辑判断,Dao层是数据访问层,与数据库进行对接。至于Mapper是mybtis框架的映射用到,mapper映射文件在dao层用。
下面是介绍一下Mapper的内置方法:
1、countByExample===>根据条件查询数量
intcountByExample(UserExampleexample);
//下面是一个完整的案列
UserExampleexample=newUserExample();
Criteriacriteria=example.createCriteria();
criteria.andUsernameEqualTo("joe");
intcount=userDAO.countByExample(example);
相当于:selectcount(*)fromuserwhereusername='joe'
2、deleteByExample===>根据条件删除多条
intdeleteByExample(AccountExampleexample);
//下面是一个完整的案例
UserExampleexample=newUserExample();
Criteriacriteria=example.createCriteria();
criteria.andUsernameEqualTo("joe");
userDAO.deleteByExample(example);
相当于:deletefromuserwhereusername='joe'
3、deleteByPrimaryKey===>根据条件删除单条
intdeleteByPrimaryKey(Integerid); userDAO.deleteByPrimaryKey(101);
相当于:
deletefromuserwhereid=101
4、insert===>插入数据
intinsert(Accountrecord);
//下面是完整的案例
Useruser=newUser();
//user.setId(101);
user.setUsername("test");
user.setPassword("123456")
user.setEmail("674531003@qq.com");
userDAO.insert(user);
相当于:
insertintouser(ID,username,password,email)values(101,'test','123456','674531003@qq.com');
5、insertSelective===>插入数据
intinsertSelective(Accountrecord);
6、selectByExample===>根据条件查询数据
List<Account>selectByExample(AccountExampleexample);
//下面是一个完整的案例
UserExampleexample=newUserExample();
Criteriacriteria=example.createCriteria();
criteria.andUsernameEqualTo("joe");
criteria.andUsernameIsNull();
example.setOrderByClause("usernameasc,emaildesc");
List<?>list=userDAO.selectByExample(example);
相当于:select*fromuserwhereusername='joe'andusernameisnullorderbyusernameasc,emaildesc
//注:在iBator生成的文件UserExample.java中包含一个static的内部类Criteria,在Criteria中有很多方法,主要是定义SQL语句where后的查询条件。
7、selectByPrimaryKey===>根据主键查询数据
AccountselectByPrimaryKey(Integerid);//相当于select*fromuserwhereid=变量id
8、updateByExampleSelective===>按条件更新值不为null的字段
intupdateByExampleSelective(@Param("record")Accountrecord,@Param("example")AccountExampleexample);
//下面是一个完整的案列
UserExampleexample=newUserExample();
Criteriacriteria=example.createCriteria();
criteria.andUsernameEqualTo("joe");
Useruser=newUser();
user.setPassword("123");
userDAO.updateByPrimaryKeySelective(user,example);
相当于:updateusersetpassword='123'whereusername='joe'
9、updateByExampleSelective===>按条件更新
intupdateByExample(@Param("record")Accountrecord,@Param("example")AccountExampleexample);
10、updateByPrimaryKeySelective===>按条件更新
intupdateByPrimaryKeySelective(Accountrecord);
//下面是一个完整的案例
Useruser=newUser();
user.setId(101);
user.setPassword("joe");
userDAO.updateByPrimaryKeySelective(user);
相当于:
updateusersetpassword='joe'whereid=101
intupdateByPrimaryKeySelective(Accountrecord);
//下面是一个完整的案例
Useruser=newUser();
user.setId(101);
user.setPassword("joe");
userDAO.updateByPrimaryKeySelective(user);
相当于:updateusersetpassword='joe'whereid=101
11、updateByPrimaryKey===>按主键更新
intupdateByPrimaryKey(Accountrecord);
//下面是一个完整的案例
Useruser=newUser();
user.setId(101);
user.setUsername("joe");
user.setPassword("joe");
user.setEmail("joe@163.com");
userDAO.updateByPrimaryKey(user);
相当于:
updateusersetusername='joe',password='joe',email='joe@163.com'whereid=101
intupdateByPrimaryKey(Accountrecord);
//下面是一个完整的案例
Useruser=newUser();
user.setId(101);
user.setUsername("joe");
user.setPassword("joe");
user.setEmail("joe@163.com");
userDAO.updateByPrimaryKey(user);
相当于:
updateusersetusername='joe',password='joe',email='joe@163.com'whereid=101
解析mapper的xml配置文件
我们来看看mybatis是怎么读取mapper的xml配置文件并解析其中的sql语句。
我们还记得是这样配置sqlSessionFactory的:
<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"> <propertyname="dataSource"ref="dataSource"/> <propertyname="configLocation"value="classpath:configuration.xml"></property> <propertyname="mapperLocations"value="classpath:com/xxx/mybatis/mapper/*.xml"/> <propertyname="typeAliasesPackage"value="com.tiantian.mybatis.model"/> </bean>
这里配置了一个mapperLocations属性,它是一个表达式,sqlSessionFactory会根据这个表达式读取包com.xxx.mybaits.mapper下面的所有xml格式文件,那么具体是怎么根据这个属性来读取配置文件的呢?
答案就在SqlSessionFactoryBean类中的buildSqlSessionFactory方法中:
if(!isEmpty(this.mapperLocations)){
for(ResourcemapperLocation:this.mapperLocations){
if(mapperLocation==null){
continue;
}
try{
XMLMapperBuilderxmlMapperBuilder=newXMLMapperBuilder(mapperLocation.getInputStream(),
configuration,mapperLocation.toString(),configuration.getSqlFragments());
xmlMapperBuilder.parse();
}catch(Exceptione){
thrownewNestedIOException("Failedtoparsemappingresource:'"+mapperLocation+"'",e);
}finally{
ErrorContext.instance().reset();
}
if(logger.isDebugEnabled()){
logger.debug("Parsedmapperfile:'"+mapperLocation+"'");
}
}
}
mybatis使用XMLMapperBuilder类的实例来解析mapper配置文件。
publicXMLMapperBuilder(Readerreader,Configurationconfiguration,Stringresource,Map<String,XNode>sqlFragments){
this(newXPathParser(reader,true,configuration.getVariables(),newXMLMapperEntityResolver()),
configuration,resource,sqlFragments);
}
privateXMLMapperBuilder(XPathParserparser,Configurationconfiguration,Stringresource,Map<String,XNode>sqlFragments){
super(configuration);
this.builderAssistant=newMapperBuilderAssistant(configuration,resource);
this.parser=parser;
this.sqlFragments=sqlFragments;
this.resource=resource;
}
接着系统调用xmlMapperBuilder的parse方法解析mapper。
publicvoidparse(){
//如果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的:
privatevoidconfigurationElement(XNodecontext){
try{
//获取mapper节点的namespace属性
Stringnamespace=context.getStringAttribute("namespace");
if(namespace.equals("")){
thrownewBuilderException("Mapper'snamespacecannotbeempty");
}
//设置当前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(Exceptione){
thrownewBuilderException("ErrorparsingMapperXML.Cause:"+e,e);
}
}
configurationElement函数几乎解析了mapper节点下所有子节点,至此mybaits解析了mapper中的所有节点,并将其加入到了Configuration对象中提供给sqlSessionFactory对象随时使用。这里我们需要补充讲一下mybaits是怎么使用XMLStatementBuilder类的对象的parseStatementNode函数借用MapperBuilderAssistant类对象builderAssistant的addMappedStatement解析MappedStatement并将其关联到Configuration类对象的:
publicvoidparseStatementNode(){
//ID属性
Stringid=context.getStringAttribute("id");
//databaseId属性
StringdatabaseId=context.getStringAttribute("databaseId");
if(!databaseIdMatchesCurrent(id,databaseId,this.requiredDatabaseId)){
return;
}
//fetchSize属性
IntegerfetchSize=context.getIntAttribute("fetchSize");
//timeout属性
Integertimeout=context.getIntAttribute("timeout");
//parameterMap属性
StringparameterMap=context.getStringAttribute("parameterMap");
//parameterType属性
StringparameterType=context.getStringAttribute("parameterType");
Class<?>parameterTypeClass=resolveClass(parameterType);
//resultMap属性
StringresultMap=context.getStringAttribute("resultMap");
//resultType属性
StringresultType=context.getStringAttribute("resultType");
//lang属性
Stringlang=context.getStringAttribute("lang");
LanguageDriverlangDriver=getLanguageDriver(lang);
Class<?>resultTypeClass=resolveClass(resultType);
//resultSetType属性
StringresultSetType=context.getStringAttribute("resultSetType");
StatementTypestatementType=StatementType.valueOf(context.getStringAttribute("statementType",StatementType.PREPARED.toString()));
ResultSetTyperesultSetTypeEnum=resolveResultSetType(resultSetType);
StringnodeName=context.getNode().getNodeName();
SqlCommandTypesqlCommandType=SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
//是否是<select>节点
booleanisSelect=sqlCommandType==SqlCommandType.SELECT;
//flushCache属性
booleanflushCache=context.getBooleanAttribute("flushCache",!isSelect);
//useCache属性
booleanuseCache=context.getBooleanAttribute("useCache",isSelect);
//resultOrdered属性
booleanresultOrdered=context.getBooleanAttribute("resultOrdered",false);
//IncludeFragmentsbeforeparsing
XMLIncludeTransformerincludeParser=newXMLIncludeTransformer(configuration,builderAssistant);
includeParser.applyIncludes(context.getNode());
//ParseselectKeyafterincludesandremovethem.
processSelectKeyNodes(id,parameterTypeClass,langDriver);
//ParsetheSQL(pre:<selectKey>and<include>wereparsedandremoved)
SqlSourcesqlSource=langDriver.createSqlSource(configuration,context,parameterTypeClass);
//resultSets属性
StringresultSets=context.getStringAttribute("resultSets");
//keyProperty属性
StringkeyProperty=context.getStringAttribute("keyProperty");
//keyColumn属性
StringkeyColumn=context.getStringAttribute("keyColumn");
KeyGeneratorkeyGenerator;
StringkeyStatementId=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))
?newJdbc3KeyGenerator():newNoKeyGenerator();
}
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语句的问题。