為了簡化 XML 的配置,MyBatis 提供了注解。我們可以通過 MyBatis 的 jar 包查看注解,如下圖所示。
以上注解主要分為三大類,即 SQL 語句映射、結(jié)果集映射和關(guān)系映射。下面分別進行講解。
@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();
以 MySQL 為例,MySQL 在插入一條數(shù)據(jù)后,使用 select last_insert_id() 可以獲取到自增 id 的值。
@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 各個屬性含義如下。
statement:表示要運行的 SQL 語句;
keyProperty:可選項,表示將查詢結(jié)果賦值給代碼中的哪個對象;
keyColumn:可選項,表示將查詢結(jié)果賦值給數(shù)據(jù)表中的哪一列;
resultType:指定 SQL 語句的返回值;
before:默認值為 true,在執(zhí)行插入語句之前,執(zhí)行 select last_insert_id()。值為 flase,則在執(zhí)行插入語句之后,執(zhí)行 select last_insert_id()。
@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);
@Param 用于在 Mapper 接口中映射多個參數(shù)。
int saveUser(@Param(value="user") User user,@Param("name") String name,@Param("age") Int age);
@Param 中的 value 屬性可省略,用于指定參數(shù)的別名。
@Result、@Results、@ResultMap 是結(jié)果集映射的三大注解。
聲明結(jié)果集映射關(guān)系代碼:
@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 各個屬性的含義。
id:表示當(dāng)前結(jié)果集聲明的唯一標識;
value:表示結(jié)果集映射關(guān)系;
@Result:代表一個字段的映射關(guān)系。其中,column 指定數(shù)據(jù)庫字段的名稱,property 指定實體類屬性的名稱,jdbcType 數(shù)據(jù)庫字段類型,id 為 true 表示主鍵,默認 false。
可使用 @ResultMap 來引用映射結(jié)果集,其中 value 可省略。
@Select({"select id, name, class_id from student where id = #{id}"}) @ResultMap(value="studentMap") Student selectById(Integer id);
這樣不需要每次聲明結(jié)果集映射時都復(fù)制冗余代碼,簡化開發(fā),提高了代碼的復(fù)用性。
@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);