一、映射Mapper
接口方法映射到对应的SQL
XXXMapper.xml的命名空间名称就是Mapper接口的全限定名
Mapper接口上也可以通过相应的注释来写SQL(但是最好不要这么写哦)
// 查询全部
// @Select("select * from employee")
List<Employee> findAll();
employeeMapper.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="cn.cxm.mapper.mapper.EmployeeMapper">
<select id="findOne" parameterType="long" resultType="cn.cxm.mapper.domain.Employee">
SELECT * FROM employee WHERE id=#{id}
</select>
<select id="findAll" parameterType="long" resultType="cn.cxm.mapper.domain.Employee">
SELECT * FROM employee
</select>
<insert id="save" parameterType="cn.cxm.mapper.domain.Employee" >
INSERT INTO employee (name,age) VALUES (#{name},#{age})
</insert>
<!--
<update id="update" parameterType="cn.cxm.mapper.domain.Employee">
UPDATE employee SET name=#{name},age=#{age} WHERE id=#{id}
</update>
-->
<delete id="delete" parameterType="long">
DELETE FROM employee WHERE id=#{id}
</delete>
<!--
添加多条数据
使用foreach标签,collection:遍历的集合,item:集合的每一个元素
separator:分离符
-->
<insert id="batchSave" parameterType="list">
INSERT INTO employee (name,age) VALUES
<foreach collection="list" item="emp" separator=",">
(#{emp.name},#{emp.age})
</foreach>
</insert>
<!--批量删除,删除一定范围,使用in( ,)-->
<delete id="batchDelete" parameterType="list">
DELETE FROM employee WHERE id in
<foreach collection="list" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
<!--模糊查询-->
<!--
<select id="queryAll" parameterType="list" resultType="cn.cxm.mapper.domain.Employee">
SELECT * FROM employee where name LIKE CONCAT("%",#{name},"%")
</select>
-->
<!--使用where标签,自动将第一个and替换为where-->
<!--多条件查询-->
<select id="queryAll" parameterType="cn.cxm.mapper.query.EmployeeQuery" resultType="cn.cxm.mapper.domain.Employee">
SELECT * FROM employee
<where>
<if test="name!=null and name!=''">
AND name LIKE CONCAT("%",#{name},"%")
</if>
<if test="minAge!=null">
AND age>=#{minAge}
</if>
<if test="maxAge!=null">
AND <![CDATA[ age<=#{maxAge}]]>
</if>
</where>
</select>
<!--查询总条数-->
<select id="count" parameterType="cn.cxm.mapper.query.EmployeeQuery" resultType="long">
SELECT count(id) FROM employee
<where>
<if test="name!=null and name!=''">
AND name LIKE CONCAT("%",#{name},"%")
</if>
<if test="minAge!=null">
AND age>=#{minAge}
</if>
<if test="maxAge!=null">
AND <![CDATA[ age<=#{maxAge}]]>
</if>
</where>
</select>
<!--动态修改,当使用动态修改,只修改其中的一条数据,同一id的其他数据不会改变-