注解@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);
结果注解有一个缺点,就是在一个查询方法前面都要写一遍,不能重用。解决这个问题方案是:
定义一份结果映射文件如下所示:
.......
@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();
}
}
原文地址