使用注解开发
使用注解可以更快更方便的实现简单的sql语句,但是复杂的sql就不建议使用注解了
基本步骤
第一步:创建方法,配置注解
@Select("select * from user where id = #{id}")
student findUserById(int id);
第二步:配置mapper映射
<select id="getUserByRowBounds" resultType="cn.yzx.pojo.student">
select * from user;
</select>
第三步:在mybatis核心配置文档注册mapper
<!--注册mapper.xml-->
<mappers>
<mapper resource="cn/yzx/mapper/stuMapper.xml" />
</mappers>
第四步:使用
@Test
public void test05() {
SqlSession sqlSession = mybatisUtil.getSqlSession();
stuMapper mapper = sqlSession.getMapper(stuMapper.class);
student userById = mapper.findUserById(95002);
System.out.println(userById);
sqlSession.close();
}
原理:
sqlSession.getMapper(stuMapper.class);传入了对应接口的class文件,框架底层会使用反射读取该接口的所有信息,包括注解,之后便可以实现很多的效果
额外补充
当形参是基本数据类型时,要加上@param(形参名称)注解修饰形参



网友评论