publicinterfaceUserMapper2{ @Select("select * from user") List<User> getAllUsers();
@Results({ @Result(property = "id", column = "id"), @Result(property = "username", column = "u"), @Result(property = "address", column = "a") }) @Select("select username as u,address as a,id as id from user where id=#{id}") User getUserById(Long id);
@Select("select * from user where username like concat('%',#{name},'%')") List<User> getUsersByName(String name);
@Insert({"insert into user(username,address) values(#{username},#{address})"}) @SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Integer.class) Integer addUser(User user);
@Update("update user set username=#{username},address=#{address} where id=#{id}") Integer updateUserById(User user);
@Delete("delete from user where id=#{id}") Integer deleteUserById(Integer id); }
这里是通过全注解的方式来写 SQL,不写 XML 文件。
@Select、@Insert、@Update 以及 @Delete 四个注解分别对应 XML 中的 select、insert、update 以及 delete 标签,@Results 注解类似于 XML 中的 ResultMap 映射文件(getUserById 方法给查询结果的字段取别名主要是向小伙伴们演示下 @Results 注解的用法)。
另外使用 @SelectKey 注解可以实现主键回填的功能,即当数据插入成功后,插入成功的数据 id 会赋值到 user 对象的id 属性上。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-21-mapper.dtd"> <mappernamespace="org.javaboy.mybatis.mapper.UserMapper"> <selectid="getAllUser"resultType="org.javaboy.mybatis.model.User"> select * from t_user; </select> <insertid="addUser"parameterType="org.javaboy.mybatis.model.User"> insert into user (username,address) values (#{username},#{address}); </insert> <updateid="updateUserById"parameterType="org.javaboy.mybatis.model.User"> update user set username=#{username},address=#{address} where id=#{id} </update> <deleteid="deleteUserById"> delete from user where id=#{id} </delete> </mapper>