mybatis中註解對映SQL示例程式碼

竹林聽雨行發表於2018-12-02
註解@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();
}}


文章摘自:

www.jb51.net/article/121…



相關文章