MyBatis注解开发
使用注解开发会比配置文件开发更容易。
-
查询:@Select
-
添加:@Insert
-
修改:@Update
-
删除:@Delete
提示:
注解完成简单功能
配置文件完成复杂功能。
使用注解来映射简单语句会使代码显得更加简洁,Java注释不仅力不从心,还会让你本就复杂的SQL语句更加混乱不堪。因此,如果你需要做一些很复杂的操作,最好用xml来映射语句。
选择何种方式来配置映射,以及认为是否应该要统一映射语句定义的形式,完全取决于你和你的团队。换句话说,永远不用拘泥于一种方式,你可以很轻松的在基于注释和xml的语句映射方式间自由移植和切换。
在UserMapper.java类中添加注解开发,就不用在映射文件添加SQL语句
@Select("select * from tb_user where id = #{id}")
User selectById(int id);
在测试类里添加方法
@Test public void testSelectById() throws IOException { //1.获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取SqlSession对象 //SqlSession sqlSession = sqlSessionFactory.openSession(); SqlSession sqlSession = sqlSessionFactory.openSession(true); //3.获取Mapper接口的代理对象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //4.执行方法 User user = userMapper.selectById(1); System.out.println(user); //提交事务 sqlSession.commit(); //5.释放资源 sqlSession.close(); }
浙公网安备 33010602011771号