Mybatis超详细讲解构建SQL方法


当前第2页 返回上一页

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内容来自木庄网络博客


打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...