mybatis框架的注意点
1.在mapper.xml文件中
resultType:返回结果类型,只能用于单表
paramsType:接收参数类型,基本数据类型可省略
2.给实体类起别名
在mybatisConfig.xml配置 <configuratoin> <typeAliases> 1.<typeAlias type="类的完整路径",alias="别名"/>
2.<package name="扫描实体类所在的包"/>,别名为类名小写 </typeAliases> <configuratoin>
3.获得新增数据的id
在Mapper.xml中的新增代码中加入 <insert userGenerateKeys="true" keyProperty="id的列名" .....
4.mybatis的in查询
- 参数类型为list集合
<select id="findall" resultType="bean.Emp"> select * from emp where empno in <foreach collection="list" item="a" open="(" separator="," close=")" > #{a} </foreach> </select>
注意:parameterType 的值可以省略 - 参数为数组
<select id="findall" resultType="bean.Emp"> select * from emp where empno in <foreach collection="array" index="b" item="a" open="(" separator="," close=")" > #{a} </foreach> </select> 注意:parameterType 的值可以省略
- 参数为map
<select id="findall" resultType="bean.Emp"> select * from emp where empno in <foreach collection="keya" index="b" item="a" open="(" separator="," close=")" > #{a} </foreach> </select> 注意:parameterType 的值可以省略 传的值: Map map=new HashMap(); map.put("keya", list1);
5.模糊查
<if test="ename!=null and ename!=''"> and ename like '%${属性名}%' </if>
注意:test属性中读取属性值时直接写属性名
模糊查询读取属性时使el 表达式,${属性名}
除以上位置外,都使用#{属性名}
多个条件时使用and,or 拼接
6.resultMap
- 单表的resultMap
resultType="指定返回值的类型"//当列名和属性名一致时使用 resultMap="aaa" //1.当列名和属性名不一致 2.做多表查询时 mybatis 能实现的是单标的自动操作 <resultMap id="aaa" type="bean.Dept"> <!-- 可以手动指定列名和属性名的关系 ,非主键列使用result 标签,主键 列使用id 标签--> <id property="dept_no" column="deptno"></id> <result property="d_name" column="dname"/> <result property="d_loc" column="loc"/> </resultMap>
- 两表关系(一对一)
<select id="方法名" resultMap="随便取"> sql语句 </select> <resultMap="对应随便取" type="实体类"> <id column="主键名称" property="对应实体类主键”> <result column="非主键名称" property="对应实体类非主键”> 存的是一方的话使用association 子标签 <association property="实体类中对应属性名" javaType="实体类名称"> <id column="主键名称" property="对应实体类主键”> <result column="非主键名称" property="对应实体类非主键”> </ association> </resultMap>
- 两表关系(多对多)
<select id="方法名" resultMap="随便取"> sql语句 </select> <resultMap="对应随便取" type="实体类"> <id column="主键名称" property="对应实体类主键”> <result column="非主键名称" property="对应实体类非主键”> 存的是集合的话使用Collection 子标签 <collection property="属性名" ofType="java 类型"> <id column="主键名称" property="对应实体类主键”> <result column="非主键名称" property="对应实体类非主键”> </ collection> </resultMap>
- 两表关系(一对多,多对一)
浙公网安备 33010602011771号