MyBatis--12.`MyBatis`注解式开发

259 阅读1分钟

MyBatis注解式开发是通过在Dao层中的方法上添加注解,从而使得程序不需要配置mapper文件;但是MyBatis还是建议使用mapper文件,因为使用配置文件会更加灵活;

1.修改StudentDao文件,为方法添加注解

public interface StudentDao {
	@Insert("INSERT INTO student(name,age,score) VALUES(#{name},#{age},#{score})")
	void insertStudent(Student student);
	
	@Insert("INSERT INTO student(name,age,score) VALUES(#{name},#{age},#{score})")
	@SelectKey(statement="select @@Identity",resultType=int.class,keyProperty="id",before=false)
	void insertStudenCacheId(Student student);
	
	@Delete("DELETE FROM student WHERE id = #{id}")
	void delectStudentById(int id);
	
	@Update("UPDATE student SET name=#{name},age=#{age},score=#{score} WHERE id = #{id}")
	void updateStudent(Student student);
	
	@Select("select id,name,age,score from student")
	List<Student> selectAllStudent();
	
	@Select("select id,name,age,score from student where id=#{id}")
	Student selectStudentById(int id);
	
	@Select("select id,name,age,score from student where name like '%' #{name} '%'")
	List<Student> selectStudentByStudentName(String name);
}

2.修改mybatis配置文件

	<!--将mapper的属性改成package-->
	<mappers>
		<package name="com.mybatis.dao"/>
	</mappers>