3 新增功能的实现
定义功能类并提供获取新增的 SQL 语句的方法。
//新增功能 //@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})") @InsertProvider(type = ReturnSql.class , method = "getInsert") public abstract Integer insert(Student stu);
属性说明:
属性 | 说明 |
---|---|
@InsertProvider | 生成新增用的 SQL 语句注解。 |
type 属性 | 生成 SQL 语句功能类对象 |
method 属性 | 指定调用方法 |
编写测试函数:
@Test public void insert() throws Exception{ //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Student stu = new Student(4,"赵六",26); Integer result = mapper.insert(stu); //6.处理结果 System.out.println(result); //7.释放资源 sqlSession.close(); is.close(); }
运行效果如下:
4 修改功能的实现
定义功能类并提供获取修改的 SQL 语句的方法。
//修改功能 //@Update("UPDATE student SET name=#{name},ag @UpdateProvider(type = ReturnSql.class , meth public abstract Integer update(Student stu);
属性说明:
属性 | 说明 |
---|---|
@UpdateProvider | 生成修改用的 SQL 语句注解。 |
type 属性 | 生成 SQL 语句功能类对象 |
method 属性 | 指定调用方法 |
编写测试函数:
@Test public void update() throws Exception{ //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Student stu = new Student(7,"赵六",36); Integer result = mapper.update(stu); //6.处理结果 System.out.println(result); //7.释放资源 sqlSession.close(); is.close(); }
运行效果如下:
5 删除功能的实现
定义功能类并提供获取删除的 SQL 语句的方法。
//删除功能 //@Delete("DELETE FROM student WHERE id=#{id}") @DeleteProvider(type = ReturnSql.class , method public abstract Integer delete(Integer id);
属性说明:
属性 | 说明 |
---|---|
@DeleteProvider | 生成删除用的 SQL 语句注解。 |
type 属性 | 生成 SQL 语句功能类对象 |
method 属性 | 指定调用方法 |
编写测试函数:
@Test public void delete() throws Exception{ //1.加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Integer result = mapper.delete(7); //6.处理结果 System.out.println(result); //7.释放资源 sqlSession.close(); is.close(); }
运行效果如下:
到此这篇关于Mybatis超详细讲解构建SQL方法的文章就介绍到这了,更多相关Mybatis构建SQL内容请搜索
更多SQL内容来自木庄网络博客
- 欢迎访问木庄网络博客
- 可复制:代码框内的文字。
- 方法:Ctrl+C。