MyBatis的CRUD操作

127 阅读1分钟

1. selectAll

编写接口方法:编写Mapper接口,无参数

结果:List<Brand>

编写SQL语句:SQL映射文件

执行方法,测试

注意事项

数据库的字段名和实体类的属性名不一样,无法封装查询出来的某些字段

  • 使用数据库查询语句的别名,把要查询的某个字段用别名表示
  • 使用映射
<resultMap id="brandResultMap" type="brand">

    <result column="brand_name" property="brandName" />

    <result column="company_name" property="companyName" />

</resultMap>
<select id="selectAll" resultMap="brandResultMap">

    select * from mybatis.tb_brand

</select>

2. selectById 通过ID查询某个数据

<select id="selectById" resultMap="brandResultMap">

    select * from mybatis.tb_brand where id=#{id}

</select>

日志中有这样2条

[DEBUG] [main] c.i.m.B.selectById - ==> Preparing: select * from mybatis.tb_brand where id=?

[DEBUG] [main] c.i.m.B.selectById - ==> Parameters: 1(Integer)

从日志中可以看到id后面是 ? 而不是具体的id,然后又把id=1作为参数传到方法里面。

如果把 select * from mybatis.tb_brand where id=#{id} 里面的#改为$符号,就不能防止SQL注入,日志是这样的

[DEBUG] [main] c.i.m.B.selectById - ==> Preparing: select * from mybatis.tb_brand where id=1 [DEBUG] [main] c.i.m.B.selectById - ==> Parameters:

3. 参数类型 parameterType可以省略

4. 特殊字符处理

由于配置文件是在xml文件里面,所以会有特殊字符报错。

  • 使用转义字符
  • 使用CDATA区