springboot

SpringBoot--实战开发--整合MyBatis(八)

2019-05-07  本文已影响180人  无剑_君

一、整合MyBatis

添加依赖:

<!--jdbc驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.11</version>
    </dependency>
    <!--jdbc 数据源-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!--mybatis-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.0.0</version>
    </dependency>
  <!-- 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

二、配置

Spring Boot 2默认数据库连接池选择了HikariCP

默认的数据库连接池由Tomcat换成HikariCP. 如果在一个Tomcat应用中用spring.datasource.type来强制使用Hikari连接池, 则可以去掉这个override.

为何选择HikariCP

HiKariCP是数据库连接池的一个后起之秀,号称性能最好,可以完美地PK掉其他连接池,是一个高性能的JDBC连接池,基于BoneCP做了不少的改进和优化。

# JDBC连接数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/iotManager?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=1234

# 数据库连接池
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
# 最小空闲连接数量
spring.datasource.hikari.minimum-idle=5
# 连接池最大连接数,默认是10
spring.datasource.hikari.maximum-pool-size=15
#此属性控制从池返回的连接的默认自动提交行为,默认值:true
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=UserHikariCP
# 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
spring.datasource.hikari.max-lifetime=1800000
#数据库连接超时时间,默认30秒,即30000
spring.datasource.hikari.connection-timeout=30000
#指定校验连接合法性执行的sql语句
spring.datasource.hikari.connection-test-query=SELECT 1

#=classpath*:mapper/**/*.xml
mybatis.mapper-locations=classpath*:/mapper/*.xml
mybatis.type-aliases-package=com.neuedu.entity

三、数据库脚本

CREATE DATABASE yige DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
use
IotManager;

/* 用户信息表 */
CREATE TABLE USER (
    id int NOT NULL auto_increment COMMENT  '用户ID',
    username varchchar(20) not null COMMENT  '用户账号',
    birthday varchchar(20) not null COMMENT '出生年月',
    sex varchchar(6) not null COMMENT '性别',
    address varchchar(30) COMMENT '地址',
    PRIMARY KEY  (`id`)
)COMMENT ='用户表' ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

/* 用户表的模拟数据 */
insert into USER(username ,birthday ,sex ,address ) values 
    ('zhangsan','1990-05-03','男','天津市滨海区'),
    ('lishui','1903-05-01','女','河北省张家口市'),
    ('wangwu','1900-08-01','女,' 河北石家庄市'),
    ('zhaoliu','1900-08-01','女,' 河北石家庄市');

四、创建Mapper文件

src\main\resources\mapper\UserMapper.xml

<?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="com.neusoft.mapper.UserMapper" >
    <resultMap id="BaseResultMap" type="com.neusoft.entity.User" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="username" property="username" jdbcType="VARCHAR" />
        <result column="birthday" property="birthday" jdbcType="DATE" />
        <result column="sex" property="sex" jdbcType="CHAR" />
        <result column="address" property="address" jdbcType="VARCHAR" />
    </resultMap>
    <sql id="Base_Column_List" >
    id, username, birthday, sex, address
  </sql>
    <select id="selectAll" resultMap="BaseResultMap" >
        select
        <include refid="Base_Column_List" />
        from user
    </select>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select
        <include refid="Base_Column_List" />
        from user
        where id = #{id,jdbcType=INTEGER}
    </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from user
    where id = #{id,jdbcType=INTEGER}
  </delete>
    <insert id="insert" parameterType="com.neusoft.entity.User" >
    insert into user (id, username, birthday,
      sex, address)
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{birthday,jdbcType=DATE},
      #{sex,jdbcType=CHAR}, #{address,jdbcType=VARCHAR})
  </insert>
    <insert id="insertSelective" parameterType="com.neusoft.entity.User" >
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                id,
            </if>
            <if test="username != null" >
                username,
            </if>
            <if test="birthday != null" >
                birthday,
            </if>
            <if test="sex != null" >
                sex,
            </if>
            <if test="address != null" >
                address,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                #{id,jdbcType=INTEGER},
            </if>
            <if test="username != null" >
                #{username,jdbcType=VARCHAR},
            </if>
            <if test="birthday != null" >
                #{birthday,jdbcType=DATE},
            </if>
            <if test="sex != null" >
                #{sex,jdbcType=CHAR},
            </if>
            <if test="address != null" >
                #{address,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="com.neusoft.entity.User" >
        update user
        <set >
            <if test="username != null" >
                username = #{username,jdbcType=VARCHAR},
            </if>
            <if test="birthday != null" >
                birthday = #{birthday,jdbcType=DATE},
            </if>
            <if test="sex != null" >
                sex = #{sex,jdbcType=CHAR},
            </if>
            <if test="address != null" >
                address = #{address,jdbcType=VARCHAR},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>
    <update id="updateByPrimaryKey" parameterType="com.neusoft.entity.User" >
    update user
    set username = #{username,jdbcType=VARCHAR},
      birthday = #{birthday,jdbcType=DATE},
      sex = #{sex,jdbcType=CHAR},
      address = #{address,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

五、创建Mapper接口

@Repository
public interface UserMapper {
    int deleteByPrimaryKey(Integer id);
    int insert(User record);
    int insertSelective(User record);
    User selectByPrimaryKey(Integer id);
    int updateByPrimaryKeySelective(User record);
    int updateByPrimaryKey(User record);
    List<User> selectAll();
}

添加扫描路径:

@SpringBootApplication
@MapperScan(value = "com.neusoft.mapper")
public class SpringbootDevPracticeApplication {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(SpringbootDevPracticeApplication.class);
        application.run(args);
    }
}

六、单元测试

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class SpringbootDevPracticeApplicationTests {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void insert(){
        User user=new User();
        user.setId(1);
        user.setSex("男");
        user.setBirthday(new Date());
        user.setAddress("天津卫");
        userMapper.insert(user);
    }
}

七、分页插件

@Test
    public void page(){
        // 参数1:当前页数
        // 参数2:每页显示的数量
        PageHelper.startPage(3, 2);
        List<User> user = userMapper.selectAll();
        // 分页的各种信息。保存在pageInfo中。可打断点查看具体内容。
        PageInfo pageInfo = new PageInfo(user);
        // 分页要显示的信息保存在 List(变量)中。getList() 获取数据。
        List list = pageInfo.getList();

        System.out.println("当前页:" + pageInfo.getPageNum());
        System.out.println("每页的数量:" + pageInfo.getPageSize());
        System.out.println("当前页显示的数量:" + pageInfo.getSize());

        //由于startRow和endRow不常用,这里说个具体的用法
        // 可以在页面中"显示startRow到endRow 共size条数据"
        // 当前页面第一个元素在数据库中的行号
        // 当前页面最后一个元素在数据库中的行号
        System.out.println("显示" + pageInfo.getStartRow() + "到" + pageInfo.getEndRow() + "共" + pageInfo.getSize() + "条数据");
        System.out.println("当前页面第一个元素在数据库中的行号: " + pageInfo.getStartRow());
        System.out.println("当前页面最后一个元素在数据库中的行号: " + pageInfo.getEndRow());
        System.out.println("总记录数: " + pageInfo.getTotal());
        System.out.println("总页数: " + pageInfo.getPages());
        System.out.println("前一页:" + pageInfo.getPrePage());
        System.out.println("下一页:" + pageInfo.getNextPage());
        System.out.println("是否为第一页:" + pageInfo.isIsFirstPage());
        System.out.println("是否为最后一页:" + pageInfo.isIsLastPage());
        System.out.println("是否有前一页:" + pageInfo.isHasPreviousPage());
        System.out.println("是否有下一页:" + pageInfo.isHasNextPage());
        System.out.println("导航页码数:" + pageInfo.getNavigatePages());
        System.out.println("所有导航页码数:");

        for (int i : pageInfo.getNavigatepageNums()) {
            System.out.println(" " + i + ",");
        }
    }

八、控制台打印SQL

  1. 添加配置
    在application.properties添加:
#mybatis日志的配置,设置成debug可以输出sql语句
logging.level.com.neusoft.mapper=debug
#开启驼峰编码
#在数据库中经常使用带下划线的命名方式,而在Java代码中,偏向于使用驼峰式的命名方式
#在SpringBoot下,整合mybatis开启驼峰法命名转换
mybatis.configuration.map-underscore-to-camel-case=true
  1. 注意
    logback-spring.xml 文件的CONSOLE与root的日志级别要一下要小于debug。
上一篇 下一篇

猜你喜欢

热点阅读