每日总结[5 20191005]MyBatis之输入输出映射

(1)头脑风暴,把我能想到的写下来:

(一) 输入输出映射部分。

先复习通过动态代理的方式实现Mybatis:
首先,新建Mapper包,其下有UserMapper接口和同名的UserMapper.xml,在SqlMapConfig.xml中写<mapper package="xxx.xx.Mapper">,进行包扫描。在接口中的方法需要与UserMapper.xml中的statement一致。
新建UserEx类,(扩展类,用于后续添加属性),和UserPacking类(包装类),其中有UserEx类型的UserEx属性。
接下来,通过Mybatis实现一些select需求:
需求1:
sql语句: select * from user where sex='1' and username like '%vin%'
如果我们不传入"1"和"%vin%"的参数,想执行全查呢,可以使用<if>标签。如果传入了性别参数就按性别参数查,如果传入了姓名参数还可以按姓名参数模糊查询,如果不传参数的话就全查。
在UserMapper.xml中写:

  <select id="queryComp"  parameterType="UserPacking" resultType="User"
  select * from user
 < where>
 <if test="userex!=null">
 <if test="userex.sex!=null">
 sex=#{userex.sex}
 </if>
 <if test="userex.name!=null">
 and username like '$%userex.name%'
 </if>
 </where>
 </select>

[改: and username like ‘%${userEx.username}%’]

因为userex是userPacking类的属性,所以<if test>中是可以通过getter方法读取到它的。
可以把上述的判断模块提出来,提取需要注意:不能有<where>,不能是多表查询:

<sql id="mySQL">
 <if test="userex!=null">
 <if test="userex.sex!=null">
 usersex=#{userex.sex}
 </if>
 <if test="userex.name!=null">
 and username like '$%userex.name%'
 </if>
</sql>
 <select id="queryComp"  parameterType="UserPacking" resultType="User"
  select * from user
 < where>
 < include refid="mySQL">
 </where>

[补充:
sql语句:select count(
) from user where…可以用来统计元组个数]
*

需求2:
sql语句:

select* from user where id='1' or id='2' or id='3'

因为这会涉及多个id,可以在UserPacking类中添加List ids属性,这样就可以通过传入UserPacking类,由它的getter方法获取ids属性,再通过标签,如下所示:

  <select id="queryByID"  parameterType="UserPacking" resultType="User">
  select * from user
  <where>
  <foreach collection="everyid" type="userex.id">
  <open="" close="" seperater="or">
  id=#{everyid}
  </where>
  </select>

[改:

<foreach collection="ids" item="everyid">
<separator>

]

这时如果提到<sql>中,需要让<if test="ids!=null">
还有一种写法:
sql语句:

select * from user where userid in('1','2','3');

对应的:

 <select id="queryByID2"  parameterType="UserPacking" resultType="User">
  select * from user
  <where>
  <foreach collection="ereryid" type="userex.id">
  <open="in (" close=")" seperater=",">
  #{everyid}
  </where>
  </select>

[改:

<foreach collection="ids" item="everyid">

]

需求三:
sql语句:select userid as myID,username as myname,useradress as myadress
其中,"as"是可以省略的。
这里就需要要到resultMap了。

<resultMap id="Ailis" type="User">
<result column="myID" property="username">
<result column="myname" property="userid">
<result column="myadress" property="useraddress">

以上所示的对应的是我们在sql语句中写的那个列名的别名,而type则是映射以后的类,而对应的是映射成的类的属性。(注意:这里必须是直接拥有的,可以通过getter方法获得的,不能是其父类的属性。)

 <select id="queryAilis"  resultMap="Ailis">
select userid as myID,username as myname,useradress as myadress
  </select>

在单元测试中输出得到的User类集合,它每个对象都会输出对应属性。

发布了47 篇原创文章 · 获赞 1 · 访问量 1282

猜你喜欢

转载自blog.csdn.net/weixin_41750142/article/details/102216820
今日推荐