目录
实体类属性名和数据库的表中列名不一致,不能自动封装数据
方法一,起别名。在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样。
方法二,resulMap。定义<resultMap>完成不一致的属性名和列名的映射。
参数占位符
1.#{}:会将其替换为?,为了防止SQL注入。效果如下:
2.${}:直接拼接SQL,存在SQL注入的问题。效果如下:
特殊字符处理
1.转义字符;
2.CDATA区。(适用于特殊字符比较多的情况)
输入CD,按回车:
将需要的字符写在里面即可:
查询-多条件查询
1.散装参数:
List<Brand>selectByCondition(@Param("status") int status, @Param("companyName") String companyName,
@Param("brandName" String brandName);
2.对象参数:(跟对象的属性名对应)
List<Brand>selectByCondition(Brand brand);
3.Map集合参数:(跟key值对应)
List<Brand>selectByCondition(Map map);
查询-动态条件查询
if:条件判断。
用恒等式WHERE 1=1解决衔接问题:
<select id="selectByCondition" resultMap="brandResultMap">
SELECT * from tb_brand
WHERE 1=1
<if test="status != null">
AND status = #{status}
</if>
<if test="companyName != null and companyName.length() > 0">
AND company_name like #{companyName}
</if>
<if test="brandName != null and brandName.length() >0">
AND brand_name like #{brandName}
</if>
</select>
用mybatis的where标签:(where 元素知道只有在一个以上的if条件有值的情况下才去插入"WHERE"子句。而且,若最后的内容是"AND"或"OR"开头的,where 元素也知道如何将他们去除。)
<select id="selectByCondition" resultMap="brandResultMap">
SELECT * from tb_brand
<where>
<if test="status != null">
AND status = #{status}
</if>
<if test="companyName != null and companyName.length() > 0">
AND company_name like #{companyName}
</if>
<if test="brandName != null and brandName.length() >0">
AND brand_name like #{brandName}
</if>
</where>
</select>
添加
<insert id="add">
insert into tb_brand(brandName, des)
values (#{brandName}, #{des});
</insert>
mybatis事务:
openSession():默认开启事务,进行增删改操作后需要使用sqlSession.commit()手动提交事务。
openSession(true):可以设置为自动提交事务(关闭事务)。
主键返回
<insert id="add" useGeneratedKeys="true" keyProperty="id">
brand.setBrandName("京城周星驰");
brand.setDes("我会加油进步");
brandMapper.add(brand);
Integer id = brand.getId();
System.out.println(id);
修改-全量修改
<update id="update">
update tb_brand
set
brandName = #{brandName},
des = #{des}
where id = #{id}
</update>
修改-动态修改
<update id="update">
update tb_brand
<set>
<if test="brandName != null and brandName.length() > 0">
brandName = #{brandName},
</if>
<if test="des != null and des.length() > 0">
des = #{des}
</if>
</set>
where id = #{id}
</update>
注意以上set标签的使用。
删除-单个
void deleteById(int id);
<delete id="deleteById">
delete from tb_brand where id = #{id};
</delete>
删除-批量
void deleteByIds(int[] ids);
<delete id="deleteByIds">
delete from tb_brand where id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
参数传递-@Param
User Select(@Param("username") String username, @Param("password") String password);
注解开发
/**
* 注解查询
*/
@Select("SELECT * FROM tb_brand where id = #{id}")
List<Brand> selectById(int id);
还有@Insert, @Delete, @update等。
补充知识:instanceof
if(object instanceof Collection) { // 当前传的参数是Collection吗?
xxx
if(object instanceof List) { // 当前传的参数是List吗?
xxx
}
}
.