【Mybatis 框架(自學)】Day06--2022/3/13
阿新 • • 發佈:2022-03-15
使用註解開發
註解僅應用於簡單的sql語句
//方法很簡單 無需用Mapper進行對映即可實現 public interface StudentMapper { //查詢所有學生方法 @Select("select * from tbstudent") List<Student> selectStudent(); //新增學生方法:Int 或 Boolean 判斷插入是否為真 @Insert("insert into tbstudent (name,gender,phone) values(#{name},#{gender},#{phone})") int addStudent(Student student); //刪除學生方法:Boolean 判斷是否刪除 @Delete("delete from tbstudent where id = #{Sid}") boolean delStudent(@Param("Sid") int id); //修改學生方法: @Update("update tbstudent set name =#{name},gender =#{gender},phone =#{phone} where id =#{id}") int updateStudent(Student student); //查詢學生方法:索引值查詢 @Select("select * from tbstudent where id =#{id}") List<Student> selectStudentById(@Param("id") Integer id); //查詢學生方法:模糊查詢 @Select("select * from tbstudent where name like #{name}") List<Student> selectStudentByName(@Param("name") String name); //查詢學生方法:Limit分頁查詢 @Select("select * from tbstudent limit #{startIndex},#{pageSize}") List<Student> selectStudentByLimit(Map<String,Object> map); //查詢學生方法:RowBounds查詢 @Select("select * from tbstudent") List<Student> selectStudentByRowBounds(); }
自動提交事務
//在MybatisUtils工具類中 可以自動設定事務的提交
public static SqlSession getConnection(){
return sqlSessionFactory.openSession(true);//如果為true,則事務自動提交
}
Param()註解
使用它,可以更加規範程式碼,進行junit測試時,程式執行時,Param()的優先順序最高
而其內容則是基本資料型別的引數或String型別
- 基本資料型別 或 String型別 需要加上
- 引用資料型別無需Param()
- 如果只有一個基本資料型別可以忽略,但建議加上
- 當我們在Sql中引用的欄位就是Param()中的屬性
@Delete("delete from tbstudent where id = #{Sid}")
boolean delStudent(@Param("Sid") int id);
LomBok
一個框架,實體類當中的getter與setter等自動生成,自行百度