首先先介绍两个对象,一个是Account,一个是QueryVo对象:
Account对象的属性:
private Integer id; //编号
private String name; //姓名
private Float money; //金额
QueryVo对象的属性:
//QueryVo对象里面包含了一个Account对象
private Account account;
//id的集合
private List<Integer> ids;
直接贴IAccountDao.xml文件的代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ysw.dao.IAccountDao">
<!--
类中的对象写法:
account.getName()
account.getMoney()
account.getId()
因为在一般情况下,在parameterType中已经提供了一个Accoun对象了,所以直接
name、id、money即可
ONGL写法:
通过对象.属性的方式
account.name
account.id
account.money
-->
<!--抽取重复的部分,使用<include refid="">来进行引用-->
<sql id="defaultSql">
select * from account
</sql>
<!--
查询所有
一般情况下使用:resultType="com.ysw.domain.Account"
如果说使用resultMap的话:就使用resultMap="id"
select * from account
-->
<select id="findAll" resultType="account">
<include refid="defaultSql"></include>
</select>
<!--根据id查询一个-->
<select id="findById" resultType="com.ysw.domain.Account" parameterType="int">
select * from account where id = #{id}
</select>
<!--
这种方式采用的是模糊查询,使用prepareStatement进行预处理的
而 '${name}'的话采用的是statement的方式来进行的
-->
<!--模糊查询-->
<select id="findByName" parameterType="String" resultType="com.ysw.domain.Account">
select * from account where name like #{name}
</select>
<!--
根据条件查询(动态条件查询)
如果if的test中有两个条件要同时满足的话,就要用and
这里使用了别名,所以参数类型parameterType用account是没问题的
-->
<select id="findAccountByCondition" resultType="account" parameterType="account">
select * from account
<where>
<if test="name != null">
and name like #{name}
</if>
<if test="money != null">
and money > 500.0
</if>
</where>
</select>
<!--根据queryVo中的id集合实现查询用户列表,其中item中的id命名决定了#{id}-->
<select id="findUserInIds" resultType="account" parameterType="queryVo">
select * from account
<where>
<if test="ids != null and ids.size() > 0">
<foreach collection="ids" open=" and id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
</mapper>
<if test=""></if>标签:
一般在test中是放一些判断的语句,比如account对象的 name != null 则说明在account对象中的name不为空;如果是多个条件的话就要使用 【and】 来表示关系“与”;
<where></where>标签:
这个跟在sql语句中的where类似,只不过只有当if标签返回true的时候才会添加进来。好比如where里面有两个if标签进行判断,一个是判断name是否为空,一个是判断money是否为空;如果两个都不为空的话就会同时加载进where语句中进行条件查询,如果有一个返回false的话,返回false的那个就不会进入where条件语句进行条件查询,而返回true的if标签就会进入where条件语句进行筛选。
<foreach></foreach>标签:
select * from account where id in (XX,XX,XX);
collection:这个表示要进行遍历的集合内容,这里ids就是一个Integer的List集合
open:open表示开始的sql语句
close:close表示结束的sql语句
item:这里指的是在进行遍历迭代的时候的每一个迭代对象id,这个id将会一个一个地放入open和close之间的"( )"里面
separator:表示进行切割所使用的字符,这里意思是使用“,”进行切割