使用注解标注sql语句

sql语句除了可以写在xml文件中,还可以使用注解标注在接口方法上面,如:

  1. @Select("select * from user where id = #{id}")
  2. User getUserById(Integer id);
  1. public void getUserById() throws IOException {
  2. //读取MyBatis的核心配置文件
  3. InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
  4. //获取SqlSessionFactoryBuilder对象
  5. SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
  6. //通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory,生产SqlSession对象
  7. SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
  8. //获取sqlSession,此时通过SqlSession对象所操作的sql都必须手动提交或回滚事务
  9. //SqlSession sqlSession = sqlSessionFactory.openSession();
  10. //创建SqlSession对象,此时通过SqlSession对象所操作的sql都会自动提交
  11. SqlSession sqlSession = sqlSessionFactory.openSession(true);
  12. //通过代理模式创建UserMapper接口的代理实现类对象
  13. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  14. //调用UserMapper接口中的方法,就可以根据UserMapper的全类名匹配元素文件,通过调用的方法名匹配映射文件中的SQL标签,并执行标签中的SQL语句
  15. User result = userMapper.getUserById(1);
  16. //提交事务
  17. //sqlSession.commit();
  18. System.out.println("result:" + result.toString());
  19. }

@Param注解

@Param注解的作用是给参数命名,参数命名后就能根据名字得到参数值,正确的将参数传入sql语句中。
使用示例:

  1. @Select("select * from user where id = #{uid}")
  2. User getUserById2(@Param("uid") Integer id);

{}中必须使用@param注解标注的uid而不能用id。
@Param注解用于给方法参数起一个名字。以下是总结的使用原则:
在方法只接受一个参数的情况下,可以不使用@Param;在方法接受多个参数的情况下,建议一定要使用@Param注解给参数命名;如果参数是 JavaBean , 则不能使用@Param;不使用@Param注解时,参数只能有一个,并且是Javabean。

xml映射和注解映射的区别

(1)xml映射可以配置一些复杂的sql,而注解映射一般都只能配置一些相对没那么复杂的sql。
(2)在实体类属性和数据库字段的名字不能对应的情况下,xml映射可以通过resultMap结果集来解决,而注解映射是没有可以设定的地方,因此比较难解决这个问题。
(3)从软件开发的角度来说,xml映射相对于注解映射来说,更加易于后期的维护。