springboot整合mybatis配置

springboot整合mybatis配置

本文只说明在springboot中配置mybatis,不涉及springboot的创建。

首先pom依赖

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

然后是application.yml(application.properties)。我用的是.yml配置文件。.yml和.properties没什么区别,差异在于yml会有层级的划分,并且注意在冒号:后面要有空格

server:
  port:8080

#数据库配置
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/nowcoder?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    username: root
    password: 123456
#模板引擎配置
  thymeleaf:
    encoding: UTF-8
    #suffix: .html  默认后缀
    #prefix: classpath:/templates/  默认前缀

mybatis:
  mapperLocations: classpath:mapper/*.xml
  config-location: classpath:mybatis-config.xml
  typeAliasesPackage: com.example.domain

从上往下说明

  • 端口设置,没什么好说的
  • 数据库配置:在我用的mysql版本中,url中的useSSLserverTimezone都是必要的,没有的话会有警告,甚至是报错。
  • 模板引擎配置:这里我用的是thymeleaf的模板引擎,它有默认前缀和后缀,我只是记录一下。
  • 最后是mybatis:我们先看一下目录结构

在这里插入图片描述

  mapperLocations: classpath:mapper/*.xml
  config-location: classpath:mybatis-config.xml
  typeAliasesPackage: com.example.domain

mybatis分别配置了这三样

  • mapper的位置,就是.xml文件的位置,如果没有配置,就默认去mapper接口类所在的包中去找。所以会发现我的目录结构是UserMapper.java和Usermapper.xml都在com/example/mapper文件夹中(虽然这两个文件在这里看好像没有在一个地方,但是在编译之后,java文件夹和resources文件夹下的文件都会编译到target中,最终结果就是这两个都会在同一个包下)

    当然,我这里已经配置了mapper的位置,com/example/mapper/UserMapper.xml文件就不会生效了,生效的是我配置的mapper/UserMapper.xml文件

  • 配置文件的位置,这里我mybatis的配置文件什么都没有写,但是还是需要有这个文件。其实包括上一个提到的mapper的位置,还有下一个会提到的实体类的别名都可以在配置文件中配置。贴一下配置文件的代码

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--以下已经在application.yml中配置过了-->
    <!--<typeAliases>-->
        <!--<package name="com.example.domain"/>-->
    <!--</typeAliases>-->
    <!--<mappers>-->
        <!--<mapper resource="mapper/UserMapper.xml"/>-->
    <!--</mappers>-->
</configuration>

  • 实体类的别名。这个包下面的实体类都可以使用别名。com.example.domain.User --> User.

差不多就是这样了,mybatis的配置很简单,在这里记录一下。最后贴一下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.example.mapper.UserMapper">
    <select id="findAllUser" resultType="User">
        select id,name from user where id = 1;
    </select>
</mapper>

namespace就是mapper类的全类名,resultType就是我们前面定义的别名,User就是com.example.domain.User的别名。

发布了29 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43094917/article/details/85720969