mybatis註解映射SQL

結果集分頁

有時咱們須要處理海量數據,因爲數據量太大,因此不能一次取出全部的數據,這時咱們就須要使用分頁功能。mybatis經過RowBounds對象提供對分頁的支持,以下所示:
<select id="findAllStudents" resultMap="StudentResult">
    select * from studdents
</select>
int offset=0;//開始位置
int limit=25;//取出的數據條數
RowBounds rowBounds=new RowBounds(offset,limit);
List<Student> list=studentMapper.findAllStudent(rowBounds);

結果處理器

有時咱們須要對查詢結果作一些特殊的處理,這個時候就須要結果處理器,舉例以下,咱們經過sql查詢學生的stud_id和name,並指望返回一個map,其中key是stud_id,value是name.
新建一個接口:
public interface ResultHandler
{
    void handleResult(ResultContext context);
}
主要處理流程:
Map<Integer , String> map=new HashMap<Integer,String>();
SqlSession sqlSession=MyBatisUtil.openSession();
sqlSession.select("com.mybatis3.mappers.StudentMapper.findAllStudents",new ResultHandler(){
    public void handlerResult(ResultContext context)
    {
        Student student=(Student)context.getResultObject();
        map.put(student.getStudId(),student.getName());
    }
})

緩存

緩存對於不少應用來講都是很重要的,由於它能提升系統的性能。mybatis內建了緩存支持,默認狀況下,一級緩存是打開的,即若是你使用相同的sqlSession接口調用相同的select查詢,查詢結果從緩存中取得而不是去查詢數據庫。
也能夠經過<cache>標籤配置二級緩存。當配置了二級緩存後,也就意味着全部的查詢結果都會被緩存,insert,update,delete語句會更新緩存,cache的緩存管理算法是LRU。除了內建的緩存以外,mybatis還整合了第三方緩存框架例如Ehcache等。

註解@Insert @Update @Select @ Delete

舉例說明註解的用法:
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);
}
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);
}
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的註解

對於動態sql,mybatis提供了不一樣的註解,@InsertProvider @UpdateProvider @DeleteProvider @SelectProvider
用法以下所示:
首先建立一個provider類:
    
    public class SqlProvider
    {
        public String findTutorById(int tutorId)
        {
            return "select tutorId,name,email from tutors where tutorId="+tutorId;
        }
    }
 使用provider類:
     @SelectProvider(type=SqlProvider.class,method="findTutorById")
     Tutor findTutorById(int tutorId);   
  可是使用字符串鏈接建立sql語句容易出現問題,因此mybatis提供了一個SQL工具,簡化了構建動態Sql的方式;
  以下所示:
    public class SqlProvider
    {
        public String findTutorById(int tutorId)
        {
            return new SQL(){{
              SELECT("tutorid,name,email")
              FROM("tutors")
              WHERE("tutorid="+tutorId)
            }}.toString();
        }
    } 
    或者 
    public class SqlProvider
    {
        public String findTutorById()
        {
            return new SQL(){{
              SELECT("tutorid,name,email")
              FROM("tutors")
              WHERE("tutorid=#{tutorId}")
            }}.toString();
        }
    }
相關文章
相關標籤/搜索