继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

SpringBoot项目实战(4):集成Mybatis

慕冬雪
关注TA
已关注
手记 78
粉丝 9131
获赞 5502

SpringBoot项目实战(1):新建Maven项目

SpringBoot项目实战(2):集成SpringBoot

SpringBoot项目实战(3):整合Freemark模板

前三节为开发SpringBoot项目的基础工作,接下来就正式开发web项目开发。本篇文章介绍SpringBoot如何集成Mybatis,往后会慢慢整理,比如整合logback日志记录、Aop、Filter、读取自定义配置文件、如何使用Idea+Maven构建SpringBoot多模块项目以及如何打包部署等等文章。

OK,继续。整合Mybatis前的准备工作:建数据库(mysql)

构建测试数据库(Mysql)

CREATE TABLE `message` (
  `ID` int(50) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `NICK_NAME` varchar(50) DEFAULT NULL COMMENT '昵称',
  `IP` varchar(50) DEFAULT NULL COMMENT 'IP',
  `INSERT_TIME` datetime DEFAULT NULL COMMENT '提交时间',
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8;

插一下哈: 是否有小伙伴经常遇到过这种情况:主键为自增,我开发期间插入了100条测试数据,开发完成后,直接通过工具导出mysql表,然后导入的生产线上的数据库中,当插入数据时,主键并不是从预想的0开始增加。曾经我就被这整懵逼过,后来下决心仔细看了看建表语句才发现了一些端倪。仔细看上面的建表语句,主键是自增的,并且在语句最后有这么一句:ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8;这句的意思依次是:使用InnoDB 引擎,自增键的起始序号为51,默认编码为UTF-8。看到了吧?就是这个东西AUTO_INCREMENT。你建表的时候改成0哈,否则你懵逼了别怨我。

另附一个批量插入的存储过程

DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `autoInsert`()
BEGIN
    DECLARE
        i INT DEFAULT 0 ; -- 开始
    SET autocommit = 0 ; -- 结束
    WHILE (i < 1000) DO
        REPLACE INTO message (
            `ID`,
            `NICK_NAME`,
            `IP`,
            `INSERT_TIME`
        )
    VALUE
        (
            i,
            'zhangyd',
            '127.0.0.1',
            NOW()
        ) ;
    SET i = i + 1 ;
    END
    WHILE ;
    SET autocommit = 1 ; COMMIT ;
    END
;;
DELIMITER ;

POM.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.blog</groupId>
    <artifactId>blog</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.7</java.version>
    </properties>
    <dependencies>
        <!--支持 Web 应用开发,包含 Tomcat 和 spring-mvc。 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--模板引擎-->
      <!--  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <!--springboot 集成Mybatis所需jar配置 start-->
        <!--支持使用 JDBC 访问数据库-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <!--Mysql / DataSource-->
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--springboot 集成Mybatis所需jar配置 end-->
        <!--Json Support-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.43</version>
        </dependency>
        <!--springboot中修改完文件后自动reload的插件,修改完文件Ctrl + F9 Make一下就可以-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
            <version>1.2.3.RELEASE</version>
        </dependency>
        <!--springboot中修改完文件后自动reload的插件 end-->
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>1.2.3.RELEASE</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
    <!--配置远程仓库地址-->
    <repositories>
        <repository>
            <id>spring-milestone</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <!--配置远程仓库地址-->
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestone</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>

application.properties文件配置

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

SB程序主函数

package com.blog;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * blog
 * Created by yadong.zhang on com.blog.application
 * User:yadong.zhang
 * Date:2016/10/20
 * Time:18:15
 */
/**
 * 1).@SpringBootApplication标注启动配置入口,run()方法会创建一个Spring应用上下文(Application Context)。
 * SpringBoot通过启动内嵌的Servlet容器(默认tomcat)用来处理Http请求。
 * 2).@RestController是特殊的Controller,他的返回值直接作为Http Response的Body部分返回给浏览器
 * 3).Spring WebMvc框架会将Servlet容器里收到的Http请求根据路径分发到对应的@Controller下进行处理。
 */
@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan
//指定扫描的mapper接口所在的包
@MapperScan("com.blog.mapper")
//启动注解事务管理
@EnableTransactionManagement
//@RestController
public class Applaction {

    private static final String TYPE_ALIASES_PACKAGE = "com.blog.model";
    private static final String MAPPER_LOCATION = "classpath:/mybatis/*.xml";
    @Bean
    @Autowired
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        //mybatis.typeAliasesPackage:指定domain类的基包,即指定其在*Mapper.xml文件中可以使用简名来代替全类名(看后边的UserMapper.xml介绍)
        sqlSessionFactoryBean.setTypeAliasesPackage(TYPE_ALIASES_PACKAGE);
        /*
            mybatis.mapperLocations:指定*Mapper.xml的位置
            如果不加会报org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.blog.mapper.MessageMapper.findMessageInfo异常
            因为找不到*Mapper.xml,也就无法映射mapper中的接口方法。
         */
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return sqlSessionFactoryBean.getObject();
    }
    public static void main(String[] args) {
        SpringApplication.run(Applaction.class, args);
    }
}

注:sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));这一句话一定要有,就是指定程序去哪儿查找Mapper.xml文件

Mapper、Mapper.xml

package com.blog.mapper;
import com.blog.model.Message;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
 * blog
 * Created by yadong.zhang on com.blog.mapper
 * User:yadong.zhang
 * Date:2016/10/21
 * Time:11:19
 */
@Repository
public interface MessageMapper{
    public List<Message> findMessageInfo();
}
<?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.blog.mapper.MessageMapper">
    <resultMap id="message_map" type="com.blog.model.Message">
        <id property="id" column="ID" jdbcType="INTEGER"></id>
        <result property="ip" column="IP" jdbcType="VARCHAR"></result>
        <result property="insertDate" column="INSERT_TIME" jdbcType="DATE"></result>
        <result property="nickName" column="NICK_NAME" jdbcType="VARCHAR"></result>
    </resultMap>
    <select id="findMessageInfo" resultMap="message_map">
        select * from message
    </select>
</mapper>

Controller(中间还有Service层以及其实现,此处略)

package com.blog.controller;
import com.blog.service.IMessageService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 * blog
 * Created by yadong.zhang on com.blog.controller
 * User:yadong.zhang
 * Date:2016/10/20
 * Time:18:26
 */
@Controller
public class HelloController {
    @Resource
    private IMessageService messageService;
    @RequestMapping("/message")
    public String message(Model model){
        model.addAttribute("messages", messageService.findMessageInfo());
        return "message";
    }
}

message.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Spring Boot 集成Mybatis 测试例子</title>
</head>
<body>
<h1>Spring Boot 集成Mybatis 测试例子</h1>
<em>${.now}</em>

<#if messages?exists>
    <table style="border: 1px solid red;">
        <#assign index = 1>
        <#list messages as message>
            <tr <#if index%2 == 0>style="color: red;"</#if>>
                <td>${message.id}</td>
                <td>${message.ip}</td>
                <td>${message.nickName}</td>
                <td>${message.insertDate?date}</td>
            </tr>
            <#assign index = index + 1>
        </#list>
    </table>
</#if>
</body>
</html>

视图结果
图片描述

OK,整合Mybatis到此结束,下节总结Spring Boot 集成分页插件

项目地址:GitHub地址,点击查看
图片描述

Github源码 - SpringBoot多模块项目

我可以对一个人无限的好,前提是值得。 ——慕冬雪

打开App,阅读手记
38人推荐
发表评论
随时随地看视频慕课网APP

热门评论

你这例子,引用 mybatis不对吧?应该:

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis-spring</artifactId>

<version>1.2.2</version>

</dependency>

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis</artifactId>

<version>3.2.8</version>

</dependency>


修改成:

<dependency>

            <groupId>org.mybatis.spring.boot</groupId>

            <artifactId>mybatis-spring-boot-starter</artifactId>

            <version>1.1.1</version>

        </dependency>


不错啊啊啊!!!!!!!!!!!

哈哈,auto-increment去掉也行

查看全部评论