Mybatis註解
阿新 • • 發佈:2020-09-09
Mybatis註解是用來替換Mybatis對映檔案的,使用註解可以減少檔案開發的數量。
Mybatis常用註解如下:
@Insert:實現新增
@Select:實現查詢
@Update:實現更新
@Delete:實現刪除
@Result:實現結果集的封裝
@Results:可以與Result一起使用,實現多個結果集的封裝
@ResultMap:實現引用@Results定義的封裝
@One:實現一對一結果集的封裝
@Many:實現一對多結果集的封裝
@SelectProvider:實現動態SQL對映
@CacheNamespace:實現註解二級快取的使用
Mybatis配置檔案設定
在使用Mybatis註解的時候需要首先配置Mybatis配置檔案中的mappers。
<mappers> <package name="org.lanqiao.dao"/> </mappers>
常用註解CRUD操作:
//不需要返回主鍵
public interface StudentMapper{ @Insert("insert into student (stud_id, name, email, addr_id, phone)values(#{studId},#{name},#{email},#{address.addrId},#{phone})") int insertStudent(Student student); }//MySQL資料庫返回主鍵 public interface StudentMapper{ @Insert("insert into student (name,email,addr_id,phone)values(#{name},#{email},#{address.addrId},#{phone})") @Options(useGeneratedKeys=true,keyProperty="studId") int insertStudent(Student student); }
//Oracle資料庫返回主鍵 public interface StudentMapper{ @Insert("insert into student (name,email,addr_id,phone)values(#{name},#{email},#{address.addrId},#{phone})") @SelectKey(statement="select stud_id_seq.nextval from dual",keyProperty="studId",resultType=int.calss,before=true) int insertStudent(Student student); }//更新操作 @Update("update students set name=#{name},email=#{email}") int updateStudent(Student student); //刪除操作 @Delete("delete form students where stud_id=#{studId}") int deleteStudent(int studId) //查詢操作 @Select("select name,email,phone from students where stud_id=#{studId}") Student findStudentById(Integer studId);
結果集註解:
@Select("select name,email,phone from students where stud_id=#{studId}") @Results({ @Result(id=true,column="stud_id",property="studId"), @Result(column="name",property="name"), @Result(column="email",property="email"), @Result(column="phone",property="phone") }) Student findStudentById(Integer studId); 結果註解有一個缺點,就是在一個查詢方法前面都要寫一遍,不能重用。解決這個問題方案是: 定義一份結果對映檔案如下所示: <mapper namespace="com.mybatis3.mappers.StudentMapper"> <resultMap type="Student" id="StudentResult"> ....... </resultMap> @Select("select name,email,phone from students where stud_id=#{studId}") @ResultMap("com.mybatis3.mappers.StudentMapper.StudentResult") Student findStudentById(Integer studId);
動態SQL註解:
方式一:
@Select("<script>select * from user <if test=\"id !=null \">where id = #{id} </if></script>") public List<User> findUserById(User user);
方式二:
@Mapper public interface MybatisDao { //使用UserDaoProvider類的findUserById方法來生成sql @SelectProvider(type = UserDaoProvider.class, method = "findUserById") public List<User> findUserById(User user); class UserDaoProvider { public String findUserById(User user) { String sql = "SELECT * FROM user"; if(user.getId()!=null){ sql += " where id = #{id}"; } return sql; } }
}