跟我一起学mybatis之注解开发---案例

举报
楠羽 发表于 2022/09/13 14:34:05 2022/09/13
【摘要】 mybatis

三.构建sql

3.1 SQL 构建对象介绍

  • 我们之前通过注解开发时,相关 SQL 语句都是自己直接拼写的。一些关键字写起来比较麻烦、而且容易出错。
  • MyBatis 给我们提供了 org.apache.ibatis.jdbc.SQL 功能类,专门用于构建 SQL 语句
    *在这里插入图片描述

3.2 查询功能的实现

  • 定义功能类并提供获取查询的 SQL 语句的方法。 

  • @SelectProvider:生成查询用的 SQL 语句注解。

    type 属性:生成 SQL 语句功能类对象

    method 属性:指定调用方法

3.3 新增功能的实现

  • 定义功能类并提供获取新增的 SQL 语句的方法。

  • @InsertProvider:生成新增用的 SQL 语句注解。

    type 属性:生成 SQL 语句功能类对象

    method 属性:指定调用方法

3.4 修改功能的实现

  • 定义功能类并提供获取修改的 SQL 语句的方法。

  • @UpdateProvider:生成修改用的 SQL 语句注解。

    type 属性:生成 SQL 语句功能类对象

    method 属性:指定调用方法

3.5 删除功能的实现

  • 定义功能类并提供获取删除的 SQL 语句的方法。

  • @DeleteProvider:生成删除用的 SQL 语句注解。

    type 属性:生成 SQL 语句功能类对象

    method 属性:指定调用方法

四.综合案例

4.1 系统介绍

​ 我们之前在做学生管理系统时,使用的是原始JDBC操作数据库的,操作非常麻烦,现在我们使用MyBatis操作数据库,简化Dao的开发。

4.2 环境搭建(略)

4.3 代码改造

  • 步骤一:新增MyBatis配置文件 MyBatisConfig.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!--MyBatis的DTD约束-->
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <!--configuration 核心根标签-->
    <configuration>
    
        <!--引入数据库连接的配置文件-->
        <properties resource="config.properties"/>
    
        <!--配置LOG4J-->
        <settings>
            <setting name="logImpl" value="log4j"/>
        </settings>
    
        <!--environments配置数据库环境,环境可以有多个。default属性指定使用的是哪个-->
        <environments default="mysql">
            <!--environment配置数据库环境  id属性唯一标识-->
            <environment id="mysql">
                <!-- transactionManager事务管理。  type属性,采用JDBC默认的事务-->
                <transactionManager type="JDBC"></transactionManager>
                <!-- dataSource数据源信息   type属性 连接池-->
                <dataSource type="POOLED">
                    <!-- property获取数据库连接的配置信息 -->
                    <property name="driver" value="${driver}" />
                    <property name="url" value="${url}" />
                    <property name="username" value="${username}" />
                    <property name="password" value="${password}" />
                </dataSource>
            </environment>
        </environments>
    
        <!--配置映射关系-->
        <mappers>
            <package name="com.itheima"/>
        </mappers>
    </configuration>
    
    
  • 步骤二: 删除StudentDaoImpl,修改StudentDao

    package com.itheima.dao;
       
    
      import com.itheima.domain.Student;
      import org.apache.ibatis.annotations.Delete;
      import org.apache.ibatis.annotations.Insert;
      import org.apache.ibatis.annotations.Select;
      import org.apache.ibatis.annotations.Update;
      import java.util.ArrayList;
    
      /*
          Dao层接口
       */
      public interface StudentDao {
          //查询所有学生信息
          @Select("SELECT * FROM student")
          public abstract ArrayList<Student> findAll();
    
      //条件查询,根据id获取学生信息
      @Select("SELECT * FROM student WHERE sid=#{sid}")
      public abstract Student findById(Integer sid);
    
      //新增学生信息
      @Insert("INSERT INTO student VALUES (#{sid},#{name},#{age},#{birthday})")
      public abstract int insert(Student stu);
    
      //修改学生信息
      @Update("UPDATE student SET name=#{name},age=#{age},birthday=#{birthday} WHERE sid=#{sid}")
      public abstract int update(Student stu);
    
      //删除学生信息
      @Delete("DELETE FROM student WHERE sid=#{sid}")
      public abstract int delete(Integer sid);
    
      }
    
    
    
  • 步骤三:修改StudentServiceImpl

    package com.itheima.service.impl;
    
    import com.itheima.dao.StudentDao;
    import com.itheima.domain.Student;
    import com.itheima.service.StudentService;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * 学生的业务层实现类
     * @author 黑马程序员
     * @Company http://www.itheima.com
     */
    public class StudentServiceImpl implements StudentService {
    
        @Override
        public List<Student> findAll() {
            ArrayList<Student> list = null;
            SqlSession sqlSession = null;
            InputStream is = null;
            try{
                //1.加载核心配置文件
                is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
                //2.获取SqlSession工厂对象
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
                //3.通过工厂对象获取SqlSession对象
                sqlSession = sqlSessionFactory.openSession(true);
    
                //4.获取StudentDao接口的实现类对象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
    
                //5.调用实现类对象的方法,接收结果
                list = mapper.findAll();
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //6.释放资源
                if(sqlSession != null) {
                    sqlSession.close();
                }
                if(is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            //7.返回结果
            return list;
        }
    
        @Override
        public Student findById(Integer sid) {
            Student stu = null;
            SqlSession sqlSession = null;
            InputStream is = null;
            try{
                //1.加载核心配置文件
                is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
                //2.获取SqlSession工厂对象
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
                //3.通过工厂对象获取SqlSession对象
                sqlSession = sqlSessionFactory.openSession(true);
    
                //4.获取StudentDao接口的实现类对象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
    
                //5.调用实现类对象的方法,接收结果
                stu = mapper.findById(sid);
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //6.释放资源
                if(sqlSession != null) {
                    sqlSession.close();
                }
                if(is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            //7.返回结果
            return stu;
        }
    
        @Override
        public void save(Student student) {
            SqlSession sqlSession = null;
            InputStream is = null;
            try{
                //1.加载核心配置文件
                is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
                //2.获取SqlSession工厂对象
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
                //3.通过工厂对象获取SqlSession对象
                sqlSession = sqlSessionFactory.openSession(true);
    
                //4.获取StudentDao接口的实现类对象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
    
                //5.调用实现类对象的方法,接收结果
                mapper.insert(student);
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //6.释放资源
                if(sqlSession != null) {
                    sqlSession.close();
                }
                if(is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        @Override
        public void update(Student student) {
            SqlSession sqlSession = null;
            InputStream is = null;
            try{
                //1.加载核心配置文件
                is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
                //2.获取SqlSession工厂对象
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
                //3.通过工厂对象获取SqlSession对象
                sqlSession = sqlSessionFactory.openSession(true);
    
                //4.获取StudentDao接口的实现类对象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
    
                //5.调用实现类对象的方法,接收结果
                mapper.update(student);
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //6.释放资源
                if(sqlSession != null) {
                    sqlSession.close();
                }
                if(is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        @Override
        public void delete(Integer sid) {
            SqlSession sqlSession = null;
            InputStream is = null;
            try{
                //1.加载核心配置文件
                is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
                //2.获取SqlSession工厂对象
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
                //3.通过工厂对象获取SqlSession对象
                sqlSession = sqlSessionFactory.openSession(true);
    
                //4.获取StudentDao接口的实现类对象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
    
                //5.调用实现类对象的方法,接收结果
                mapper.delete(sid);
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //6.释放资源
                if(sqlSession != null) {
                    sqlSession.close();
                }
                if(is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。