MyBatis注解提出,可以说是非常好简化了MyBatis配置文件的使用。下面我们简单地来告诉大家如何使用MyBatis的注解
- 定义接口
package com.gxa.dao; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.gxa.pojo.Teacher; public interface TeacherDao { @Insert("insert into teacher (t_id,t_name) values (#{t_id},#{t_name})") public intinsertTeacher(Teacher teacher); @Update("update teacher set t_name=#{t_name} where t_id=#{t_id}") public intupdateTeacher(Teacher teacher); @Delete("delete from teacher where t_id = #{t_id}") public intdeleteTeacher(intt_id); @Select("select * from teacher") public List<Teacher>getTeacher(); }
- 在MyBatis核心配置文件注册好映射接口
<mapper class="com.gxa.dao.TeacherDao"/>
- 马上来使用Java程序来测试一下
package com.gxa.test; import java.io.IOException; import java.io.Reader; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import com.gxa.dao.TeacherDao; import com.gxa.pojo.Student; import com.gxa.pojo.Teacher; public class Test04 { private static SqlSessionFactorysqlSessionFactory; private static Reader reader; static { try { reader = Resources.getResourceAsReader("config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } @Test public void m01() { SqlSessionsqlSession = sqlSessionFactory.openSession(); TeacherDaoteacherDao = sqlSession.getMapper(TeacherDao.class); List<Teacher> list = teacherDao.getTeacher(); for (Teacher teacher : list) { System.out.println(teacher.getT_id() + "=====" + teacher.getT_name()); } sqlSession.close(); } }