跳到主要内容

基本增删改查

Mybatis获取参数值

#{}和${}

  • ${}的本质就是字符串拼接,#{}的本质就是占位符赋值
  • ${}使用字符串拼接的方式拼接SQL,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号
  • #{}使用占位符赋值的方式拼接SQL,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号(推荐使用)

注意:使用${}会有SQL注入的风险

单个参数

  • 若mapper接口中的方法参数为单个
  • 此时可以使用${}和#{}以任意的名称获取参数的值

如:User selectUserById(Long id);

多个参数

  • 若mapper接口中的方法参数为多个时
  • 此时MyBatis会自动将这些参数放在一个map集合中,以arg0,arg1...为键,以参数为值;以param1,param2...为键,以参数为值

如:User selectUserByAgeWithNameBegin(Integer age, String name);

实体类类型的参数

  • 若mapper接口中的方法参数为实体类对象时
  • 此时可以使用${}和#{},通过访问实体类对象中的属性名获取属性值

如:Integer insertUser(User user);

使用@Param标识参数(推荐)❤

  • 通过@Param注解标识mapper接口中的方法参数

  • 参数将放在map集合中,以@Param注解的value属性值为键,以参数为值;以param1,param2...为键,以参数为值

如:Integer updateUserAgeById(@Param("age") Integer age, @Param("id") Long id);

insert

接口方法

Integer insertUser(User user);

映射文件

<insert id="insertUser">
insert into user(id, name, age, email)
values (#{id}, #{name}, #{age}, #{email})
</insert>

update

接口方法

Integer updateUserAgeById(@Param("age") Integer age, @Param("id") Long id);

映射文件

<update id="updateUserAgeById">
update user
set age = #{age}
where id = #{id}
</update>

delete

接口方法

 Integer deleteUserById(@Param("id") Long id);

映射文件

 <delete id="deleteUserById">
delete
from user
where id = #{id}
</delete>

select

查询一个实体类对象

接口方法

User selectUserById(@Param("id") Long id);

映射文件

<select id="selectUserById" resultType="user">
select id, name, age, email
from user
where id = #{id}
</select>

查询一个List集合

接口方法

List<User> selectAllUser();

映射文件

<select id="selectAllUser" resultType="user">
select id, name, age, email
from user
</select>

查询单个数据

在Mybatis 中,java中常用的类型都设置了别名

接口方法

String selectUserNameById(@Param("id") Long id);

映射文件

<select id="selectUserNameById" resultType="string">
select name
from user
where id = #{id}
</select>

模糊查询

通过#{}查询(推荐)❤

接口方法

List<User> selectUserIncludeName(@Param("name") String name);

映射文件

<select id="selectUserIncludeName" resultType="top.hyqstudio.pojo.User">
select id, name, age, email
from user
where name like concat('%', #{name}, '%')
</select>

通过${}查询

注意:此种方式会存在SQL注入的情况

接口方法

List<User> selectUserIncludeName(@Param("name") String name);

映射文件

<select id="selectUserIncludeName" resultType="top.hyqstudio.pojo.User">
select id, name, age, email
from user
where name like '%${name}%'
</select>