MyBatis基于代理模式开发

129 阅读2分钟

MyBatis基于代理模式开发

代理模式开发的注意事项

1、Mapper映射的名字必须和接口的名字保持一致,扩展名不算

2、Maper映射文件的namespace必须是接口的全路径名。 例:com.jdl.mapper.EmpMapper

3、sql语句的id必须和抽象方法的名一致

4、DeptMapper映射文件应该和接口编译之后放在同一个目录下

参数传递问题

单个参数作为方法参数

单个基本数据类型作为方法参数
#{}中可以随便写,遵循见名知意
 <select id="findByEmpno" resultType="emp" >
        select * from emp where empno =#{empno}
 </select>

多个参数作为方法参数

多个基本数据类型作为方法参数
 List<Emp> findByDeptnoAndSal(@Param("detpno") int deptno,@Param("sal") double sal);
 方式1 arg*     arg0 arg1 arg2 数字是索引,从0开始
 方式2 param*   param1 param2 param3 数字是编号,从1开始
 使用别名
 List<Emp> findByDeptnoAndSal(@Param("detpno") int deptno,@Param("sal") double sal);
 通过@Param注解使用别名之后,就不能再使用arg* 但是可以继续使用param*
<select id="findByDeptnoAndSal" resultType="emp">
        <!--select * from emp where deptno =#{arg0} and sal >= #{arg1}-->
        <!-- select * from emp where deptno =#{param1} and sal >= #{param2}-->
        select * from emp where deptno =#{deptno} and sal >= #{sal}
</select>

参数为map,#{键的名字}

单个引用类型,#{对象的属性名}

模糊查询

/**  接口的抽象方法
 * 根据名字做模糊查询
 * @param name 模糊查询的文字
 * @return  Emp对象List集合
 */
List<Emp> findByEname( String name);
<!--xml配置文件里的实现方法-->
<!--List<Emp> getByName(String name);-->
<select id="findByEname"  resultType="emp" >
    select * from emp where ename like concat('%',#{name},'%')
</select>

主键自增回填

//接口
public interface DeptMapper {
    int addDept(Dept dept);
    int addDept2(Dept dept);
}
   <!-- int addDept(Dept dept);
   useGeneratedKeys="true" 返回数据库帮我们生成的主键
   keyProperty="deptno" 生成的主键值用我们dept对象那个属性存储
   -->
    <insert id="addDept" parameterType="dept" useGeneratedKeys="true" keyProperty="deptno">
        insert into dept values(null,#{dname},#{loc})
    </insert>

既要低头拉车,也要抬头看路
谢谢!