mybatis映射XML文件详解及实例
mybatis映射XML文件
一个简单的映射文件:
当然这个文件中没有任何的元素
TheMapperXMLfileshaveonlyafewfirstclasselements:
- cache–Configurationofthecacheforagivennamespace.
- cache-ref–Referencetoacacheconfigurationfromanothernamespace.
- resultMap–Themostcomplicatedandpowerfulelementthatdescribeshowtoloadyourobjectsfromthedatabaseresultsets.
- sql–AreusablechunkofSQLthatcanbereferencedbyotherstatements.
- insert–AmappedINSERTstatement.
- update–AmappedUPDATEstatement.
- delete–AmappedDELETEstatement.
- select–AmappedSELECTstatement.
select
简单的例子:
SELECT*FROMPERSONWHEREID=#{id}
select也有很多属性可以让你配置:
insert,updateanddelete
语句:
insertintoAuthor(id,username,password,email,bio) values(#{id},#{username},#{password},#{email},#{bio}) updateAuthorset username=#{username}, password=#{password}, email=#{email}, bio=#{bio} whereid=#{id} deletefromAuthorwhereid=#{id}
fyourdatabasesupportsauto-generatedkeyfields(e.g.MySQLandSQLServer),上面的插入语句可以写成:
insertintoAuthor(username,password,email,bio) values(#{username},#{password},#{email},#{bio})
如果你的数据库还支持多条记录插入,可以使用下面这个语句:
insertintoAuthor(username,password,email,bio)values (#{item.username},#{item.password},#{item.email},#{item.bio})
sql
这个element可以定义一些sql代码的碎片,然后在多个语句中使用,降低耦合。比如:
${alias}.id,${alias}.username,${alias}.password
然后在下面的语句中使用:
select , fromsome_tablet1 crossjoinsome_tablet2
ResultMaps
官网给了个最最复杂的例子
大体意思呢就是一个博客系统有一个作者,很多博文,博文中有一个作者,很多评论,很多标签(包括了一对多,一对一)
select B.idasblog_id, B.titleasblog_title, B.author_idasblog_author_id, A.idasauthor_id, A.usernameasauthor_username, A.passwordasauthor_password, A.emailasauthor_email, A.bioasauthor_bio, A.favourite_sectionasauthor_favourite_section, P.idaspost_id, P.blog_idaspost_blog_id, P.author_idaspost_author_id, P.created_onaspost_created_on, P.sectionaspost_section, P.subjectaspost_subject, P.draftasdraft, P.bodyaspost_body, C.idascomment_id, C.post_idascomment_post_id, C.nameascomment_name, C.commentascomment_text, T.idastag_id, T.nameastag_name fromBlogB leftouterjoinAuthorAonB.author_id=A.id leftouterjoinPostPonB.id=P.blog_id leftouterjoinCommentConP.id=C.post_id leftouterjoinPost_TagPTonPT.post_id=P.id leftouterjoinTagTonPT.tag_id=T.id whereB.id=#{id}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!