SpringBoot整合Mybatis入門案列

SpringBoot整合Mybatis入門案列


1、 創建SpringBoot工程,引入依賴

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-jdbc</artifactId>
 </dependency>
 <dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>1.3.2</version>
 </dependency>
 <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <scope>runtime</scope>
 </dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2、創建配置文件

在resources目錄下創建springboot的配置文件,application.yml
在該文件中寫mysql和mybatis的配置信息。數據庫的配置信息因人而異

server:
  port: 8080
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/crud?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
mybatis:
   mapper-locations: classpath:mapper/*Mapper.xml
   type-aliases-package: com.jd.entity

3、建立目錄

在這裏插入圖片描述
其中mapper目錄下保存mybatis的sql配置文件。

<?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.jd.dao.DeptMapper">

  <resultMap id="deptMap" type="com.jd.entity.Dept">
      <id column="dept_id" property="deptId"/>
      <result column="dept_name" property="deptName"/>
  </resultMap>
  <select id="findAll" resultMap="deptMap">
      select * from dept;
  </select>
</mapper>

4、 啓動類上加掃描註解

掃描dao所在的包,也可以在dao接口上加@Mapper註解

@SpringBootApplication
@MapperScan("com.jd.dao")
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class,args);
    }
}

5、啓動

在這裏插入圖片描述
訪問8080端口,就ok了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章