• SpringBoot入门 (六) 数据库访问之Mybatis


    本文记录学习在SpringBoot中使用Mybatis。

    一 什么是Mybatis

      MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录(官方定义);

    官方使用示例代码如下:

    String resource = "org/mybatis/example/mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession session = sqlSessionFactory.openSession();
    try {
      BlogMapper mapper = session.getMapper(BlogMapper.class);
      Blog blog = mapper.selectBlog(101);
    } finally {
      session.close();
    }

    通过示例程序可以看到它的执行过程主要有以下几个步骤:

      1 应用程序启动时,根据配置文件生成一个SqlSessionFactory;

      2 通过SqlSessionFactory的到一个SqlSession;

      3 SqlSession内部通过Excutor执行对应的SQl;

      4 返回处理结果;

      5 释放资源;

    二 SpringBoot集成Mybatis

      Mybatis使用有2中方式,一种是使用注解,即在接口定义的方法上通过注解写入要执行的SQL和要完成的数据映射;一种是使用xml配置文件即在xml文件中写相关SQL和完成表与实体的映射。本文我们使用xml文件。

      首先需要引入SpringBoot集成Mybatis的依赖jar包,这里我们只引入了Spring与Mybatis集成的包,springboot默认会自动帮我们引入其他依赖的jar包。

    <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.2</version>
            </dependency>

    在application.properties文件中配置数据库连接信息和指定mybatis的接口对应的xml

    #datasoure
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/test
    spring.datasource.username=root
    spring.datasource.password=123456
    #mybatis
    mybatis.mapper-locations=classpath:mybatis/*.xml

    如上,我们的mapper xml文件放在reources目录下的mybatis文件夹下

    写一个接口,定义我们要完成的功能

    @Mapper
    public interface UserMapper {
    
        /**
         * 根据ID删除
         */
        int deleteByPrimaryKey(Long id);
    
        /**
         * 新增
         */
        int insert(UserInfo record);
    
        /**
         * 根据ID查询
         */
        UserInfo selectByPrimaryKey(Long id);
    
        /**
         * 修改
         */
        int updateByPrimaryKey(UserInfo record);
    
        /**
         * 查询所有
         */
        List<UserInfo> selectAll();
    }
    
    
    

    @Mapper 该注解说名当前类是一个Mybatis的Mapper接口类,交给spring管理,令一种方式是使用注解 @MapperScan(basePackages="...") 说明basePackages及其子包下的接口都交给spring管理,我们多数情况下都会使用@MapperScan这个注解,这样我们就不用在每一个Mapper接口上写注解了。
    在xml文件中完成SQl,实现具体的方法,如下:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="org.allen.demo.dao.UserMapper" >
      <resultMap id="BaseResultMap" type="org.allen.demo.domain.UserInfo" >
        <id column="id" property="id" jdbcType="BIGINT" />
        <result column="age" property="age" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />
      </resultMap>
      <sql id="Base_Column_List" >
        id, age, name
      </sql>
      <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
        select 
        <include refid="Base_Column_List" />
        from t_user
        where id = #{id,jdbcType=BIGINT}
      </select>
      <select id="selectAll" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from t_user
      </select>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
        delete from t_user
        where id = #{id,jdbcType=BIGINT}
      </delete>
      <insert id="insert" parameterType="org.allen.demo.domain.UserInfo" useGeneratedKeys="true" keyProperty="id">
        insert into t_user (id, age, name)
        values (#{id,jdbcType=BIGINT}, #{age,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR})
      </insert>
      <update id="updateByPrimaryKey" parameterType="org.allen.demo.domain.UserInfo" >
        update t_user
        set age = #{age,jdbcType=INTEGER},
          name = #{name,jdbcType=VARCHAR}
        where id = #{id,jdbcType=BIGINT}
      </update>
    </mapper>
    

     从这个xml文件,我们可以看到以下几点:

    namespace="org.allen.demo.dao.UserMapper" 通过namespace来指定将当前xml文件的SQL实现的对应的接口Mapper

    2 通过 resultMap 完成实体类与数据库表字段的映射

    3 xml中的SQL语句都必须写在<select> <insert> <update><delete>内部

    4 每一个标识的id都必须与接口中的方法名保持一直

    5 insert 中使用的 useGeneratedKeys 设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。如果设置了true,我们就可以在insert完成后直接通过当前操作的实体类获取数据库主键。

    三 测试

      使用Junit做测试

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class MybatisApplicationTests {
    
        @Resource
        private UserMapper userMapper;
    
        @Test
        public void save() {
            UserInfo user = new UserInfo();
            user.setName("world");
            user.setAge(2);
            userMapper.insert(user);
            System.out.println("保存后的ID:" + user.getId());
        }
    
        @Test
        public void delete() {
            long id = 5;
            userMapper.deleteByPrimaryKey(id);
        }
    
        @Test
        public void update() {
            UserInfo user = new UserInfo();
            user.setName("world");
            user.setAge(5);
            long id = 3;
            user.setId(id);
            userMapper.updateByPrimaryKey(user);
        }
    
        @Test
        public void selectById() {
            long id = 3;
            userMapper.selectByPrimaryKey(id);
        }
    
        @Test
        public void selectAll() {
            List<UserInfo> userList = userMapper.selectAll();
        }
        
    }
    

      

  • 相关阅读:
    POJ 2342
    SHU 413
    SHU 414
    进制转换模板
    SHU 第15届上海大学程序设计联赛夏季赛[热身赛] 第三题(G题)
    POJ 3185
    XTU 1260
    高斯消元法模板
    POJ 2057
    模态窗口的定时关闭
  • 原文地址:https://www.cnblogs.com/love-wzy/p/10334259.html
Copyright © 2020-2023  润新知