mybatis之@Select、@Insert、@Delete、@Param

时间:2023-03-09 04:12:45
mybatis之@Select、@Insert、@Delete、@Param

之前学习的时候,看到别人在使用mybatis时,用到@Select、@Insert、@Delete、@Param这几个注解,故楼主研究了一下,在这里与大家分享

当使用这几个注解的时候,可以省去写Mapper.xml等一系列配置文件

首先来看个例子:

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update; import com.xwj.entity.UserEntity; public interface UserMapper { /**
* 查询
*/
@Select("SELECT id, last_name lastName, email, age FROM xwj_user WHERE id = #{id} and last_name like '%${lastName}%' ")
UserEntity findById(@Param("id") String id, @Param("lastName") String name); /**
* 新增
*/
@Insert("INSERT INTO xwj_user(id, last_name, age) VALUES(#{id}, #{lastName}, #{age})")
int addUser(@Param("id") String id, @Param("lastName") String name, @Param("age") Integer age); /**
* 更新
*/
@Update("UPDATE xwj_user SET last_name = #{lastName} WHERE id = ${id}")
int updateUser(@Param("id") String id, @Param("lastName") String name); /**
* 删除
*/
@Delete("DELETE FROM xwj_user WHERE id = ${id}")
int deleteUser(@Param("id") String id);

还有实体类:

public class UserEntity {

    private String id;

    private String lastName;

    private String email;

    private int age;

    //TODO set跟get方法略。。。

}

这里解释一下:

  1、@Select(...)注解的作用就是告诉mybatis框架,执行括号内的sql语句

  2、id, last_name lastName, email, age  对于实体类字段与数据库字段表不一致时,得加上别名。如last_name是数据库字段,lastName是实体类字段

   这段代码的作用就是实现数据库字段名和实体类属性的一一映射。如果没有加别名,则在查询出的entity中,这个字段是null

  3、WHERE id = #{id} and last_name like '%${lastName}%' 表示sql语句要接受2个参数:id跟lastName。#{..}(或${..})中的名称得跟@Param(..)中的名称对应。

    这就是@Param注解的妙用,正确的将参数传入sql语句中

  4、使用了@Param注解来声明参数时,使用 #{} 或 ${}来接收参数的方式都可以

  5、@Insert、@Update、@Delete的用法跟@Select类似

  楼主在使用的过程中,发现就insert语句写在@Update注解中也是可以的

  虽然直接使用注解很方便,不过楼主发现,如果在添加查询语句时,如a字段为空则不添加,有值则添加的场景,处理起来很不方便