以上注解主要分为三大类,即 SQL 语句映射、结果集映射和关系映射。下面分别进行讲解。
@Insert("insert into user(id,name) values(#{id},#{name})") public int insert(User user);
@Select("Select * from user") @Results({ @Result(id = true, column = "id", property = "id"), @Result(column = "name", property = "name"), @Result(column = "sex", property = "sex"), @Result(column = "age", property = "age") }) List<User> queryAllUser();
@Insert("insert into user(id,name) values(#{id},#{name})") @SelectKey(statement = "select last_insert_id()", keyProperty = "id", keyColumn = "id", resultType = int,before = false) public int insert(User user);@SelectKey 各个属性含义如下。
@Insert("insert into user(name,sex,age) values(#{name},#{sex},#{age}") int saveUser(User user);
@Update("update user set name= #{name},sex = #{sex},age =#{age} where id = #{id}") void updateUserById(User user);
@Delete("delete from user where id =#{id}") void deleteById(Integer id);
int saveUser(@Param(value="user") User user,@Param("name") String name,@Param("age") Int age);@Param 中的 value 属性可省略,用于指定参数的别名。
@Select({"select id, name, class_id from student"}) @Results(id="studentMap", value={ @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true), @Result(column="name", property="name", jdbcType=JdbcType.VARCHAR), @Result(column="class_id ", property="classId", jdbcType=JdbcType.INTEGER) }) List<Student> selectAll();下面为 @Results 各个属性的含义。
@Select({"select id, name, class_id from student where id = #{id}"}) @ResultMap(value="studentMap") Student selectById(Integer id);这样不需要每次声明结果集映射时都复制冗余代码,简化开发,提高了代码的复用性。
@Select("select * from student") @Results({ @Result(id=true,property="id",column="id"), @Result(property="name",column="name"), @Result(property="age",column="age"), @Result(property="address",column="address_id",one=@One(select="net.biancheng.mapper.AddressMapper.getAddress")) }) public List<Student> getAllStudents();
@Select("select * from t_class where id=#{id}") @Results({ @Result(id=true,column="id",property="id"), @Result(column="class_name",property="className"), @Result(property="students", column="id", many=@Many(select="net.biancheng.mapper.StudentMapper.getStudentsByClassId")) }) public Class getClass(int id);
本文链接:http://task.lmcjl.com/news/7200.html