1. 程式人生 > 實用技巧 >SpringBoot整合mybatis快速入門

SpringBoot整合mybatis快速入門

一、建立一個SpringBoot專案

二、引入相關依賴

        <!--web核心依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--mysql資料庫驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

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

三、建立如下結構檔案

  • 編寫實體類com.zhg.demo.mybatis.entity.User
public class User implements Serializable {
    private Long id;//編號
    private String username;//使用者名稱
    private String password;//密碼
    //省略get set方法
}
  • 編寫介面com.zhg.demo.mybatis.mapper.UserMapper
    注意:需要使用@Mapper註解,不然SpringBoot無法掃描
@Mapper//指定這是一個操作資料庫的mapper
public interface UserMapper {
    List<User> findAll();
}
  • 編寫在resources檔案中建立 mapper/UserMapper.xml檔案
    注意
    1.namespace中需要與使用@Mapper的介面對應
    2.UserMapper.xml檔名稱必須與使用@Mapper的介面一致
    3.標籤中的id必須與@Mapper的介面中的方法名一致,且引數一致
<?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.zhg.demo.mybatis.mapper.UserMapper">
    <select id="findAll" resultType="User">
        SELECT * FROM tb_user
    </select>
</mapper>

-----------------------------------------------------------
<?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.example.demo.mapper.UserMapper">
<select id="findAll" resultType="com.example.demo.entity.User">
SELECT * FROM tb_user
</select>
</mapper>
  • 編寫介面com.zhg.demo.mybatis.service
public interface UserService {
    List<User> findAll();
}
  • 編寫實現類com.zhg.demo.mybatis.service.impl.UserServiceimpl
    注意:需要在介面實現類中使用@Service註解,才能被SpringBoot掃描,在Controller中使用@Authwired注入
@Service("userService")
public class UserServiceimpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }
}
  • 編寫api介面com.zhg.demo.mybatis.controller.UserController
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/findAll")
    public List<User> findAll(){
        return userService.findAll();
    }

}
  • 在啟動類中新增對@MapperScan的掃描
@SpringBootApplication
@MapperScan("com.zhg.demo.mybatis.mapper")//使用MapperScan批量掃描所有的Mapper介面;
public class MybatisApplication {

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

}

四、配置檔案

注意
1.mybatis中的mapper-locations是mapper的xml檔案位置
2.mybatis中的type-aliases-package是為了配置xml檔案中resultType返回值的包位置,如果未配置請使用全包名如下:

<select id="findAll" resultType="com.zhg.demo.mybatis.entity.User">
        SELECT * FROM tb_user
</select>
  • 在resources中建立application.yml檔案,並編寫配置
server:
  port: 8081
spring:
  #資料庫連線配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://47.107.105.158:3306/test?characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456

#mybatis的相關配置
mybatis:
  #mapper配置檔案
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.zhg.demo.mybatis.entity
  #開啟駝峰命名
  configuration:
    map-underscore-to-camel-case: true

--------------------------------------------------------------------------
server:
port: 8081
spring:
#資料庫連線配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf-8&useSSL=false
username: root
password: root

#mybatis的相關配置
mybatis:
#mapper配置檔案
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.demo.entity
#開啟駝峰命名
configuration:
map-underscore-to-camel-case: true

五、建立資料庫和資料表

-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES ('1', 'laowang', '112233');
INSERT INTO `tb_user` VALUES ('2', 'laoli', '123456');

六、啟動並測試



作者:蜻蜓隊長家長
連結:https://www.jianshu.com/p/541874714907
來源:簡書
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。