原文链接:http://blog.csdn.net/laiwanwanyihao/article/details/72943421,是本博主写的,
附源码,免费下载
前言
好久没用过mybatis了,现在复习一下,顺带着整理一下东西,
本人maven用的不好,架构参照来源http://www.cnblogs.com/GarfieldEr007/p/5746263.html,
本片文章例子为简单的小例子,参考的文章也是介绍mybatis,不过我没看,我就下了maven架构就开始搞自个的例子了,因为原博主的文章写得太长了,懒得看了
maven架构
maven构架springMvc+mybatis这里我就不一一展示了,想必各位都知道,不清楚的看源码就行了,
数据库
数据库很简单 三个表 A AB B 其中AB为中间表,A 与 B 为多对多关系,,,今天就整理下A与B多对多和A与AB一对多的两种关联映射处理,(注意数据库中表字段不要重名,比如A表主键与B表主键不要重名,不然查出来结果会不全,陷这个坑好久才明白过来)
多对多
- <!-- 多对多 -->
- <resultMap id="BaseResultMap2" type="cn.test.model.A">
- <id column="aid" property="aid" jdbcType="INTEGER" />
- <result column="a_name" property="aname" jdbcType="VARCHAR" />
- <collection property="bLists" ofType="cn.test.model.B">
- <id property="bid" column="bid" />
- <result property="bname" column="b_name" />
- </collection>
- </resultMap>
- <select id="selectAByIdUnionB" resultMap="BaseResultMap2"
- parameterType="java.lang.Integer">
- select
- *
- from a inner join a_b on a.aid = a_b.a_id inner
- join b on a_b.b_id = b.bid where a.aid=#{id jdbcType="INTEGER"}
- </select>
- //多对多
- @org.junit.Test
- public void seectAByIdUnionB() {
- for(A a:aService.selectAByIdUnionB(1)){
- System.out.print(a.getAname()+">>>>>>>");
- for(B b :a.getbLists() ){
- System.out.print(b.getBname());
- }
- System.out.println("\n");
- }
- }
结果
一对多
- <!-- 一对多 -->
- <resultMap type="cn.test.model.A" id="OneToManay">
- <id column="aid" property="aid" jdbcType="INTEGER" />
- <result column="a_name" property="aname" jdbcType="VARCHAR" />
- <collection property="abLists" ofType="cn.test.model.AB">
- <id property="id" column="id" />
- <result property="a" column="a_id" />
- <result property="b" column="b_id" />
- </collection>
- </resultMap>
- <select id="selectAtoAB" resultMap="OneToManay" parameterType="INTEGER">
- select * from a inner join a_b on a.aid=a_b.a_id where a.aid=#{id jdbcType="INTEGER"}
- </select>
测试
- //一对多
- @org.junit.Test
- public void onetomany(){
- for(A a :aService.selectAtoAB(1)){
- System.out.print(a.getAname()+">>>>>>>");
- for (AB ab : a.getAbLists()) {
- System.out.print(ab.getId());
- //System.out.print(ab.getA());
- //System.out.print(ab.getB());
- }
- System.out.println("\n");
- }
- }
结果

好了 希望给各位需要的同志们有所帮助,
源码下载地址:http://download.csdn.NET/detail/laiwanwanyihao/9865160
