- insert/update/delete可以设置有返回值,确定成功条数
以下deleteById返回值的int即为删除成功的条数
@Mapper
public interface UserMapper {
@Select("select * from test.t_user")
List<User> getAll();
@Delete("delete from test.t_user where id = #{id}")
int deleteById(Long id);
}
- Mybatis执行的Sql语句控制台打印在application.properties中的配置
# mybatis日志输出道控制台配置
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
- Sql注入的一种情况,Mybatis使用 ${}会产生SQL注入
这里使用' or '1' = '1
进行了密码的注入
select * from user where name = 'zs' and pwd = '111';
select * from user where name = 'zs' and pwd = '' or '1' = '1';
这样使用也会出现SQL注入(${username}):
@Select("select * from test.t_user where username like '%${username}%' and entry_date >= #{entryDateStart} and entry_date <= #{entryDateEnd}")
List<User> getUsers(String username, LocalDate entryDateStart, LocalDate entryDateEnd);
如果传入的username为以下,则可以查询到数据:
' or '%' = '
可以使用concat('%', 'zs', '%')
解决SQL注入,但是如果为查询参数为'
,会报错。
- Mybatis插入数据后获取id
在Mapper的插入方法上加上注解,keyProperty指的是将生成的id设置到对象的id属性上去
@Options(useGeneratedKeys = true, keyProperty = "id") // 获取自增主键值
- Mybatis数据库字段和实体属性不一致如何处理
别名或者使用以下注解进行映射
@Results(
{
@Result(property = "deptId", column = "dept_id"),
@Result(property = "createTime", column = "create_time"),
@Result(property = "entryDate", column = "entry_date")
}
)
或者application.properties使用
# mybatis配置驼峰命名转换
mybatis.configuration.map-underscore-to-camel-case=true
开启驼峰命名自动转换
- resources下面创建目录使用类似
com/xx/mybatis/maper
的形式,不要使用.
- Mybatis动态标签
<set>
标签会去掉内容后面的逗号,
,如下面的username = #{username},
update test.t_user
<set>
<if test="username != null">
username = #{username},
</if>
<if test="age != null">
age = #{age}
</if>
</set>
where id = #{id}
</update>
<where>
标签或去掉前面的and
或者or
<where>
<if test="username != null">
and username like concat('%', #{username}, '%')
</if>
<if test="entryDateStart != null">
and entry_date >= #{entryDateStart}
</if>
<if test="entryDateEnd != null">
and entry_date <= #{entryDateEnd}
</if>
</where>
-
MybatisX生成Mybatis代码(生成实体类,mapper,mapper.xml)
Idea安装MybatisX插件
Idea连接数据库
选择表,再选择MybatisX-Generator
modulepath和base package选择自己的,base package形如com.xxx.xxx
记得修改mapperXml的package name,template我这里不是mybatis-plus,所以选的default-all,不会生成service和comtroller,只有domain和mapper
Finish即可 -
Mac单元测试生成cmd+shift+t,可以生成类和方法,但是方法没有内容,然后结合CodeGeex可以快速创建单元测试