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("674531003@qq.com"); userdao.insert(user);
相当于:
insert into user(id,username,password,email) values(101,'test','123456','674531003@qq.com');
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("joe@163.com"); userdao.updatebyprimarykey(user);
相当于:
update user set username='joe',password='joe',email='joe@163.com' where id=101
int updatebyprimarykey(account record); //下面是一个完整的案例 user user =new user(); user.setid(101); user.setusername("joe"); user.setpassword("joe"); user.setemail("joe@163.com"); userdao.updatebyprimarykey(user);
相当于:
update user set username='joe',password='joe',email='joe@163.com' 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语句的问题。
推荐阅读
-
Java的MyBatis框架中Mapper映射配置的使用及原理解析
-
Java的MyBatis框架中XML映射缓存的使用教程
-
Java的MyBatis框架中关键的XML字段映射的配置参数详解
-
Java的MyBatis框架中关键的XML字段映射的配置参数详解
-
Java的MyBatis框架中Mapper映射配置的使用及原理解析
-
Java的MyBatis框架中XML映射缓存的使用教程
-
mybatis框架中的 mybatis-config-xml 核心配置文件 以及mapper.xml映射配置文件
-
Java的MyBatis框架中XML映射缓存的使用教程
-
Java的MyBatis框架中XML映射缓存的使用教程