SpringBoot整合Mybatis,使用mapper开发

1、创建springboot项目,添加依赖,依赖有jpa、mybatis、mysql

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- jdbc链接容器 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!-- jpa(已包含hibernate) -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--Mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>${mybatis.spring.boot.starter.version}</version>
</dependency>

2、创建开发包层级

3、再配置文件中配置jpa和mybatis、数据库相关等。尤其注意mapper相关配置

server:
  port: 80
  tomcat:
    uri-encoding: UTF-8
    max-threads: 800
    min-spare-threads: 30
  servlet:
    context-path: /
    session:
      timeout: 30
spring:
  freemarker:
    template-loader-path: classpath:/templates/
    cache: false
    charset: UTF-8
    check-template-location: true
    content-type: text/html
    expose-request-attributes: true
    expose-session-attributes: true
    request-context-attribute: request
    suffix: .html
    settings:
      number_format: '0.##'
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/one_smile?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: root

  thymeleaf:
    prefix: classpath:/templates/
    check-template-location: true
    cache: false
    suffix: .html
    mode: LEGACYHTML5
    encoding: UTF-8
    servlet:
      content-type: text/html
mybatis:
  type-aliases-package: com.one.smile.dream.entity
  mapperLocations: classpath*:mapper/*.xml
  configuration:
    cache-enabled: true

4、书写后台(一下内容截图说明重点)

第一步:创建实体类。主键字段注解掉的东西是在使用jpa方式开发的时候用的,意思是主键id使用自增uuid。这里我们使用mybatis的mapper开发。

第二步:创建业务层接口

第三步:创建业务层接口实现类。注意业务层接口实现类上面要有注解@Service,后面括号内是给该service起的别名,在后面controller层会用到。在下面截图中,我们只关注SysModelMapper,不关注SystemRepo,因为SystemRepo是jpa方式

第四步:创建mapper接口。注意mapper接口上需要使用注解@Mapper说明它是mapper接口

第五步:修改启动类。注意@MapperScan注解内的值是上面mapper接口所在的包位置

第六步,创建对应mapper接口的xml文件。注意mapper开发的四个规则

第六步:创建controlle

以上就是springboot整合mybatis使用mapper开发的流程。springboot开发一般都使用jpa方式开发。至于我为什么推崇mapper方式,原因在于mapper方式可以更好的书写复杂的sql语句,完全可以使用jpa和mapper开发结合的方式加快开发,简单语句交给jpa,复杂语句交给mapper。

最后把我关键目录层级展开看看

猜你喜欢

转载自blog.csdn.net/qq_40386113/article/details/106685882