8.mybatis与SpringBoot集成

本来想写一篇关于ssm集成方面的文章,但是考虑到现在基本上使用的是SpringBoot框架进行开发,因此直接写SpringBoot框架集成mybatis更好。

一、创建maven项目并导入相应的包

<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.qiu</groupId>
    <artifactId>mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.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.8</java.version>
    </properties>

    <dependencies>
    <!-- springboot 热部署插件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- springboot集成mybatis需要的包 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <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>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>
        <!-- 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>
        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.0</version>
        </dependency>
        <!-- mybatis代码生成器相关的包 -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>
    </build>
</project>

二、mysql中创建数据表

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) DEFAULT NULL,
  `user_password` varchar(255) DEFAULT NULL,
  `user_email` varchar(255) DEFAULT NULL,
  `user_info` varchar(255) DEFAULT NULL,
  `head_img` varchar(255) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

三、使用代码生成器自动生成相关的entity、xxxMapper和xxxMapper映射文件。

参照之前的mybatis代码生成器使用博客:https://www.jianshu.com/p/b6a0ac3ba17c

  • 在生成的xxxMapper接口上加上@Mapper注解,否则Springboot扫描不到该接口,会报错误。然后自定义一个方法
@Mapper
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>findAllUser();
}
  • 生成的model类
public class User {
    private Integer id;
    private String userName;
    private String userPassword;
    private String userEmail;
    private String userInfo;
    private String headImg;
    private Date createTime;
    ...省略getter/setter
  • 把UserMapper.xml文件放在src/main/resource/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.qiu.mapper.UserMapper">
  <resultMap id="BaseResultMap" type="com.qiu.model.User">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="user_name" jdbcType="VARCHAR" property="userName" />
    <result column="user_password" jdbcType="VARCHAR" property="userPassword" />
    <result column="user_email" jdbcType="VARCHAR" property="userEmail" />
    <result column="user_info" jdbcType="VARCHAR" property="userInfo" />
    <result column="head_img" jdbcType="VARCHAR" property="headImg" />
    <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
  </resultMap>
  <sql id="Base_Column_List">
    id, user_name, user_password, user_email, user_info, head_img, create_time
  </sql>
   <!-- 增加自己增加的方法 -->
  <select id="findAllUser" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"></include>
    from user
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    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.qiu.model.User">
    insert into user (id, user_name, user_password, 
      user_email, user_info, head_img, 
      create_time)
    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{userPassword,jdbcType=VARCHAR}, 
      #{userEmail,jdbcType=VARCHAR}, #{userInfo,jdbcType=VARCHAR}, #{headImg,jdbcType=VARCHAR}, 
      #{createTime,jdbcType=TIMESTAMP})
  </insert>
  <insert id="insertSelective" parameterType="com.qiu.model.User">
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="userName != null">
        user_name,
      </if>
      <if test="userPassword != null">
        user_password,
      </if>
      <if test="userEmail != null">
        user_email,
      </if>
      <if test="userInfo != null">
        user_info,
      </if>
      <if test="headImg != null">
        head_img,
      </if>
      <if test="createTime != null">
        create_time,
      </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="userPassword != null">
        #{userPassword,jdbcType=VARCHAR},
      </if>
      <if test="userEmail != null">
        #{userEmail,jdbcType=VARCHAR},
      </if>
      <if test="userInfo != null">
        #{userInfo,jdbcType=VARCHAR},
      </if>
      <if test="headImg != null">
        #{headImg,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.qiu.model.User">
    update user
    <set>
      <if test="userName != null">
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userPassword != null">
        user_password = #{userPassword,jdbcType=VARCHAR},
      </if>
      <if test="userEmail != null">
        user_email = #{userEmail,jdbcType=VARCHAR},
      </if>
      <if test="userInfo != null">
        user_info = #{userInfo,jdbcType=VARCHAR},
      </if>
      <if test="headImg != null">
        head_img = #{headImg,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null">
        create_time = #{createTime,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.qiu.model.User">
    update user
    set user_name = #{userName,jdbcType=VARCHAR},
      user_password = #{userPassword,jdbcType=VARCHAR},
      user_email = #{userEmail,jdbcType=VARCHAR},
      user_info = #{userInfo,jdbcType=VARCHAR},
      head_img = #{headImg,jdbcType=VARCHAR},
      create_time = #{createTime,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

四、创建一个配置类,并配置好分页插件

@Configuration
public class MybatisConfig {
    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper=new PageHelper();
        Properties properties=new Properties();
//该参数默认为false ,设置为true时,会将RowBounds第一个参数offset当
//成pageNum页码使用,和startPage中的pageNum效果一样
        properties.setProperty("offsetAsPageNum","true");
//该参数默认为false,设置为true时,使用RowBounds分页会进行count查询 
        properties.setProperty("rowBoundsWithCount","true");
//分页参数合理化,默认false禁用
        properties.setProperty("reasonable","true");
//配置mysql数据库方言
        properties.setProperty("dialect","mysql");
        pageHelper.setProperties(properties);
        return pageHelper;
    }
}

五、创建UserService和UserServiceImp

  • UserService接口
public interface UserService {
    int addUser(User user);
    List<User> findAllUser(int pageNum, int pageSize);
}
  • UserServiceImp实现类
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public int addUser(User user) {
        return userMapper.insert(user);
    }
    @Override
    public List<User> findAllUser(int pageNum, int pageSize) {
        //进行分页,必须在mybatis从数据库获取数据之前
        PageHelper.startPage(pageNum, pageSize);
        List<User> findAllUser = userMapper.findAllUser();
        return findAllUser;
    }
}

六、创建controller,执行web相关操作

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/addUser")
    public String addUser() {
        User user=new User();
        user.setCreateTime(new Date());
        user.setUserEmail("111@qq.com");
        user.setUserInfo("hahah");
        user.setUserName("qiu");
        user.setUserPassword("1233");
        int addUser = userService.addUser(user);
        return addUser!=0?"插入成功":"插入失败";
    }
    @RequestMapping("/getUserByPage")
//默认pageNum为1,pageSize为1
    public String getUsersByPage(@RequestParam(value="pageNum",defaultValue="1")Integer pageNum,
     @RequestParam(value="pageSize",defaultValue="2")Integer pageSize) {
         List<User> list = userService.findAllUser(pageNum, pageSize);
         list.forEach(System.out::println);
         return list.toString();
    }

七、创建springboot启动类

@SpringBootApplication
public class SpringbootMybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisApplication.class, args);
    }
}

八、在classpath目录下面创建SpringBoot配置文件application.properties

#tomcat端口
server.port=8082
#datasource
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# 数据库访问配置
# 主数据源,默认的
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.s
tat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
spring.datasource.useGlobalDataSourceStat=true

#mybatis相关
#别名
mybatis.type-aliases-package=com.qiu.model
#映射配置文件位置
mybatis.mapper-locations=classpath:mapper/*.xml

九、启动SpringBoot项目并进行访问

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 Mybatis入门 1.1 单独使用jdbc编程问题总结 1.1.1 jdbc程序 上边使...
    哇哈哈E阅读 3,333评论 0 38
  • 开罗 午夜里,我独自在偌大的房间里辗转难眠。窗外稀稀疏疏的蛐蛐蝈蝈演奏曲,不间断地从白色的百叶窗的夹缝里钻进来。空...
    修墨68阅读 401评论 0 1
  • 前些天看了一篇谈论自由意志的公号文章,其中讲到了神经科学论的实验研究引发的对于是否存在自由意志的怀疑,并且用另一个...
    YousoBlind_9f1f阅读 594评论 0 1
  • “把金钱当做某种行为的外部奖励时,行为主体就失去了对这项活动的内在兴趣"奖励只能带来短期的爆发,就像是少量咖啡因只...
    榛果Latte阅读 218评论 0 1
  • 句子:“自己思考原本就是件很快乐的事情,而教别人思考则是学习思考,锻炼思考的最好方法。” “只有学会真正地思考,才...
    不加奶糖的咖啡阅读 292评论 2 1