MyBatis提供了多种的注解映射,如SELECT、UPDATE、INSERT和DELETE。让我主详细来看一下这些映射的应用。
我们可以使用@Insert注解来声明一个INSERT的映射。
package com.owen.mybatis.mappers; public interface StudentMapper { @Insert("INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,ADDR_ID, PHONE) VALUES(#{studId},#{name},#{email},#{address.addrId},#{phone})") int insertStudent(Student student); }
在insertStudent()方法中,我们注解了@Insert,这个将会返回受影响的行数通过insert的声明。
在前面我们使用xml的文件时,我们声明了自动生成主键的语句。这注解的方法中,我们同样可能用@Options的方法来注解声明生成主键,这个方法中包含useGeneratedKeys和keyProperty的参数。这两个参数就是要让数据可以形成auto_increment的列值,其值是已经的列中某个对象的列作为值。
@Insert("INSERT INTO STUDENTS(NAME,EMAIL,ADDR_ID, PHONE) VALUES(#{name},#{email},#{address.addrId},#{phone})") @Options(useGeneratedKeys=true, keyProperty="studId") int insertStudent(Student student);
这里的STUD_ID的列将会通过MYSQL的数据库自动生成,和它值将和studId的值是一样的。
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); mapper.insertStudent(student); int studentId = student.getStudId();
有的数据库,如Oracle不能提供AUTO_INCREMENT列和我们需要使用SEQUENCE去形成主键。我们可以使用@Selectkey的注解去指定任何SQL的声明,而且可以作为主键的值。
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); mapper.insertStudent(student); int studentId = student.getStudId();
这里我们应用@SelectKey来生成主键的值,并且储蓄在Student的studId的属性中。因为我们定义了before=true,所以在插入时,就已经生成好了主键了。
如果你使用SEQUENCE的触发器来生成主键,我们可以从sequence_name.currval中获取主键,之后执行插入语句。
@Insert("INSERT INTO STUDENTS(NAME,EMAIL,ADDR_ID, PHONE) VALUES(#{name},#{email},#{address.addrId},#{phone})") @SelectKey(statement="SELECT STUD_ID_SEQ.CURRVAL FROM DUAL", keyProperty="studId", resultType=int.class, before=false) int insertStudent(Student student);
我们可以使用@Update注解来声明UPDATE。
@Update("UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, PHONE=#{phone} WHERE STUD_ID=#{studId}") int updateStudent(Student student);
在updateStudent()的方法中,我们使用了@Update的注解,并且会返回受影响的行。
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); int noOfRowsUpdated = mapper.updateStudent(student);
我们可以用@Delete来实现DELETE的声明。
@Delete("DELETE FROM STUDENTS WHERE STUD_ID=#{studId}") int deleteStudent(int studId);
deleteStudent()的方法将会返回受影响的行。
我们可以使用@Select注解来实现SELECT的映射 。
package com.owen.mybatis.mappers; public interface StudentMapper { @Select("SELECT STUD_ID AS STUDID, NAME, EMAIL, PHONE FROM STUDENTS WHERE STUD_ID=#{studId}") Student findStudentById(Integer studId); }
为了匹配上Student对象的实例,我们使用studId作为stud_id的别名。如何返回有多个行的值,那么将会报TooManyResultException的错。