代码:G:\CODE_MY\heimabase\mybatis\03\day03_eesy_02datasourceSQLMy
首先看下typeAlises和Package的设计:
<!--使用typeAliases配置别名,它只能配置domain中类的别名 -->
<typeAliases>
<package name="com.itheima.domain"></package>
</typeAliases>
<!-- 配置映射文件的位置 -->
<mappers>
<package name="com.itheima.dao"></package>
</mappers>
为什么出现动态的sql:我们根据条件查询的话传一个对象不确定条件是什么的时候要用到条件查询的。
/**
* 根据传入参数条件
* @param user 查询的条件:有可能有用户名,有可能有性别,也有可能有地址,还有可能是都有
* @return
*/
List<User> findUserByCondition(User user);
这个是新的写法,注意不可以使用&&要用and
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
select * from user
<where>
<if test="userName != null">
and username = #{userName}
</if>
<if test="userSex != null">
and sex = #{userSex}
</if>
</where>
</select>
老的写法。
windows的sql语句的内容是无关大小写的,实体类就是#对应的要大小写敏感。
---------------------------------------------------01----------------------------------------------------------------------
如何解决where 1=1问题?
老的写法:
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
select * from user where 1=1
<if test="userName != null">
and username = #{userName}
</if>
<if test="userSex != null">
and sex = #{userSex}
</if>
</select>
新的写法:
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
select * from user
<where>
<if test="userName != null">
and username = #{userName}
</if>
<if test="userSex != null">
and sex = #{userSex}
</if>
</where>
</select>
-----------------------------------------------------02---------------------------------------------------------------------
foreach标签。
item是遍历的每一项 separator是以,分割。
<!-- 根据queryvo中的Id集合实现查询用户列表 -->
<select id="findUserInIds" resultMap="userMap" parameterType="queryvo">
select * from user
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in (" close=")" item="uid" 这个是uid
separator=",">
#{uid} 这个也得是uid
</foreach>
</if>
</where>
</select>
/**
* 测试foreach标签的使用
*/
@Test
public void testFindInIds(){
QueryVo vo = new QueryVo();
List<Integer> list = new ArrayList<Integer>();
list.add(41);
list.add(42);
list.add(46);
vo.setIds(list);
//5.执行查询所有方法
List<User> users = userDao.findUserInIds(vo);
for(User user : users){
System.out.println(user);
}
}
-----------------------------------------------
知识点:
抽取重复的sql语句。
<!-- 了解的内容:抽取重复的sql语句-->
<sql id="defaultUser">
select * from user
</sql>
<!-- 根据queryvo中的Id集合实现查询用户列表 -->
<select id="findUserInIds" resultMap="userMap" parameterType="queryvo">
<include refid="defaultUser"></include>
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in (" close=")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>
举例:
抽取的代码片段不要写分号。
-----------------------------------------------------03---------------------------------------------------------------------