总结
Mybatis增强
-
对多个数据进行操作
<!-- mybatis会把集合或者数组放入map中 如果是集合,key默认是list 如果是数组,key默认就是array foreach:遍历标签 collection:要遍历的对象(key) separator:每遍历一次的分隔符 open:遍历开始前加的符号 close:遍历后加的符号 --> <!--void delete(List<Long> ids);--> <delete id="delete"> DELETE FROM product where id in <foreach collection="list" item="d" open="(" close=")" separator=","> #{d} </foreach> </delete>
-
表多对一的情况
<!--方式一--> <resultMap id="empResultMap" type="cn.itsource._02_many2one.domain.Employee"> <id column="id" property="id"></id> <result column="name" property="name"></result> <!-- 这个字段是对象 --> <association property="dept" javaType="cn.itsource._02_many2one.domain.Department"> <id column="did" property="id"></id> <result column="dname" property="name"></result> </association> </resultMap> <!--List<Employee> findAll();--> <select id="findAll" resultMap="empResultMap"> SELECT e.*,d.id did,d.name dname from employee e,department d WHERE e.dept_id=d.id </select>
<!--方式二--> <resultMap id="empResultMap" type="cn.itsource._02_many2one.domain.Employee"> <id column="id" property="id"></id> <result column="name" property="name"></result> <association property="dept" column="dept_id" select="deptByDeptId" javaType="cn.itsource._02_many2one.domain.Department"> </association> </resultMap> <select id="deptByDeptId" resultType="cn.itsource._02_many2one.domain.Department"> SELECT * FROM department WHERE id=#{id} </select> <!--List<Employee> findAll();--> <select id="findAll" resultMap="empResultMap"> SELECT * from employee </select>
-
表一对多的情况
<!--方式一--> <resultMap id="deptResultMap" type="cn.itsource._03_.one2many.domain.Department"> <id column="id" property="id"></id> <result column="name" property="name"></result> <!-- 这里的字段是集合类型 --> <collection property="emp" ofType="cn.itsource._03_.one2many.domain.Employee"> <id column="eid" property="id"></id> <result column="ename" property="name"></result> </collection> </resultMap> <!--List<Department> findAll();--> <select id="findAll" resultMap="deptResultMap"> SELECT d.*,e.id eid,e.name ename FROM department d,employee e WHERE d.id=e.dept_id </select>
<!--方式二--> <resultMap id="deptResultMap" type="cn.itsource._03_.one2many.domain.Department"> <id column="id" property="id"></id> <result column="name" property="name"></result> <collection property="emp" column="id" select="empByDeptId" ofType="cn.itsource._03_.one2many.domain.Employee"> </collection> </resultMap> <select id="empByDeptId" resultType="cn.itsource._03_.one2many.domain.Employee"> SELECT * from employee where dept_id = #{id} </select> <!--List<Department> findAll();--> <select id="findAll" resultMap="deptResultMap"> SELECT * FROM department </select>