SpringBoot整合Mybatis入门案列

SpringBoot整合Mybatis入门案列


1、 创建SpringBoot工程,引入依赖

<dependency>
     <groupId>org.springframework.bootgroupId>
     <artifactId>spring-boot-starter-jdbcartifactId>
 dependency>
 <dependency>
     <groupId>org.mybatis.spring.bootgroupId>
     <artifactId>mybatis-spring-boot-starterartifactId>
     <version>1.3.2version>
 dependency>
 <dependency>
     <groupId>mysqlgroupId>
     <artifactId>mysql-connector-javaartifactId>
     <scope>runtimescope>
 dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
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、建立目录

SpringBoot整合Mybatis入门案列_第1张图片
其中mapper目录下保存mybatis的sql配置文件。



<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了。

你可能感兴趣的:(spring-boot)