SpringBoot(二)springboot整合mybatis

      在我们的项目开发中,数据库的访问及存储都是最为核心的部分,SpringBoot为我们提供了多种数据库来做数据的存储及读取。目前企业开发中应用最为广泛的数据库有,关系型数据库MySQL,oracle,sqlserver,非关系型数据库redis,mongodb等。
       本章将通过使用SpringBoot访问MySQL结合Mybatis完成CRUD(Create,Read,Update,Delete)简单操作。

   项目目录结构:

   1. 创建user表

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

   2. 添加依赖

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.45</version>
    </dependency>
    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!--阿里数据连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.1.0</version>
    </dependency>

MyBatis-Spring-Boot-Starter依赖将会提供如下

  • 自动检测现有的DataSource
  • 将创建并注册SqlSessionFactory的实例,该实例使用SqlSessionFactoryBean将该DataSource作为输入进行传递
  • 将创建并注册从SqlSessionFactory中获取的SqlSessionTemplate的实例。
  • 自动扫描您的mappers,将它们链接到SqlSessionTemplate并将其注册到Spring上下文,以便将它们注入到您的bean中。

   就是说,使用了该Starter之后,只需要定义一个DataSource即可(application.properties中可配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。

     2.  数据源DataSource配置

  • 通过注解扫描的方式实现实现,在启动类中加上注解@MapperScan
@SpringBootApplication
@MapperScan("com.uv.boot.dao")
public class BootApplication {

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

  本次项目使用的使peoperties配置文件,若使用yml作为配置文件,可进行转换----转换链接。配置文件如下:

spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=
#用于搜索类型别名的包,即和数据库表对应的实体类
mybatis.type-aliases-package=com.uv.boot.entity

      3. 编写实体类 user

package com.uv.boot.entity;
/*
 * @author uv
 * @date 2018/9/14 14:29
 *
 */

public class User {

    private int id;
    private String name;
    private String password;
    
    //省略getter,setter
}

     4. 编写mapper文件和接口

 UserMapper:

package com.uv.boot.dao;
import com.uv.boot.entity.User;

/*
 * @author uv
 * @date 2018/9/14 14:45
 *
 */
public interface UserMapper {

    int insertUser(User user);

    User getUserById(int id);
}

 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.uv.boot.dao.UserMapper">
  <insert id="insertUser">
    INSERT INTO user(name, password) VALUES (#{name}, #{password})
  </insert>

  <select id="getUserById" resultType="com.uv.boot.entity.User">
    SELECT * FROM user WHERE user.id = #{id}
  </select>
</mapper>

     5. 编写UserService 和 UserController

package com.uv.boot.service;

import com.uv.boot.dao.UserMapper;
import com.uv.boot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/*
 * @author uv
 * @date 2018/9/14 14:56
 *
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public int insertUser(User user) {
        return userMapper.insertUser(user);
    }

    public User getUser(int id) {
        return userMapper.getUserById(id);
    }
}
package com.uv.boot.controller;

import com.uv.boot.entity.User;
import com.uv.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/*
 * @author uv
 * @date 2018/9/14 14:59
 *
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("insertuser")
    public String insertUser(User user) {
        int flag = userService.insertUser(user);
        return flag == 1 ? "success" : "error";
    }

    @GetMapping("getuser")
    public User getUser(int id) {
        return userService.getUser(id);
    }

}

      4. 测试

使用PostMan进行rest接口测试,如下图所示:

      5. 出现的问题

在整合完mybatis后进行测试时,出现如下错误:

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.uv.boot.dao.UserMapper.getUserById
	at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:225) ~[mybatis-3.4.5.jar:3.4.5]
	at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:48) ~[mybatis-3.4.5.jar:3.4.5]
	at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65) ~[mybatis-3.4.5.jar:3.4.5]
	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58) ~[mybatis-3.4.5.jar:3.4.5]
	at com.sun.proxy.$Proxy62.getUserById(Unknown Source) ~[na:na]

问题解决参考:https://blog.csdn.net/qq_22200097/article/details/82704283

猜你喜欢

转载自blog.csdn.net/qq_22200097/article/details/82701711