mybatis集成springboot
首先添加数据库支持,以及jdbc驱动
<!-- 数据库支持-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
在springboot中的application.yml配置文件中添加配置,其中需要根据实际情况进行更改
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
#要连接的数据库的ip地址,端口号,数据库这三个参数需要根据实际情况编写
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
#用户名和密码要根据实际情况进行填写
username: root
password: 123456
创建接口,配置接口扫描,可以在接口上通过@Mapper进行接口的注册,或者通过在主启动类中配置@MapperScan,参数必须对应mapper接口所在的位置,下面两种方法任选其一
@Mapper
public interface AuthorityDao {
ArrayList<String> qryByUser(@Param("user") User user);
}
@SpringBootApplication
@MapperScan("com.example.pasturemanage.mapper")
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
如果在resources添加了mapper文件夹,而且mapper.xml文件都在此文件夹内,则需要在application.yml中添加如下配置
mybatis:
mapper-locations: classpath:mappers/*.xml
如果在mapper文件夹内,则需要配置编译路径
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
mapper.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="映射类名">
<resultMap type="com.entity.User" id="ApplyRecordMap">
<result property="id" column="ID"/>
<result property="name" column="name"/>
</resultMap>
<sql id="Base_column_list">
`id`,
`name`,
`password`
</sql>
</mapper>
逆向工程
通过逆向工程可以对数据库表所对应的mapper文件以及mapper接口进行自动生成
首先添加逆向工程插件
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
创建名称为generatorConfig.xml配置文件,有几处需要修改,
<classPathEntry location=此处要需要加入jdbc驱动的绝对路径
<jdbcConnection 四项连接信息可以参考application.yml配置文件内的连接信息
<javaModelGenerator 配置实体类生成位置
<sqlMapGenerator 配置mapper的xml文件生成位置
<javaClientGenerator 配置mapper接口的生成位置
<table tableName="user" domainObjectName="User" 配置表名和实体类名称对应关系
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<classPathEntry location="E:\java\repository\mysql\mysql-connector-java\5.1.9\mysql-connector-java-5.1.9.jar"></classPathEntry>
<!-- 配置 table 表信息内容体,targetRuntime 指定采用 MyBatis3 的版本 -->
<context id="tables" targetRuntime="MyBatis3">
<!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 配置数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password="123">
</jdbcConnection>
<!-- 生成model类,targetPackage指定domain类的包名, targetProject指定生成的domain放在IDEA的哪个工程下面-->
<javaModelGenerator targetPackage="com.example.springboot_001_demo_homework.domain"
targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
</javaModelGenerator>
<!-- 生成MyBatis的Mapper.xml文件,targetPackage指定mapper.xml文件的包名, targetProject指定生成的mapper.xml放在IDEA的哪个工程下面 -->
<sqlMapGenerator targetPackage="com.example.springboot_001_demo_homework.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成MyBatis的Mapper接口类文件,targetPackage指定Mapper接口类的包名, targetProject指定生成的Mapper接口放在IDEA的哪个工程下面 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.springboot_001_demo_homework.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 数据库表名及对应的 Java 模型类名 -->
<table tableName="student" domainObjectName="Student"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
mybatis的日志使用
#在springboot中使用mybatis,如果需要控制台打印日志,只要在配置文件中添加如下配置
#properties中
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#yml中
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
需要注意的是,如果使用的是mybatis-plus,则需要使用如下配置
#properties中
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#yml中
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mybatis分页查询
添加依赖
<!--分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
在查询语句上添加分页语句
//此处pageNum是页码数,pageSize是每页数量
int pageNum = 1;
int pageSize = 3;
PageHelper.startPage(pageNum, pageSize);
List<User> list = userDao.queryAll();
//使用pageInfo可以查询一些详细的信息
PageInfo<User> pageInfo = new PageInfo<>(list);
//获取数据总条数
long total = pageInfo.getTotal();
//获取数据总页数
int pages = pageInfo.getPages();
//获取每页数量
int pageSize1 = pageInfo.getPageSize();
//获取当前页码
int pageNum1 = pageInfo.getPageNum();
//获取上一页页码
int prePage = pageInfo.getPrePage();
//获取下一页页码
int nextPage = pageInfo.getNextPage();
mybatis常见问题
使用分页插件出现循环依赖,报错如下,可以使用如下三种解决方式
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
┌──->──┐
| com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration
└──<-──┘
Action:
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
如果出现循环依赖,可以检查一下版本,尝试降低springboot版本
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/>
</parent>
也可以尝试提高分页插件版本,测试过1.4.0会出现循环依赖,1.4.1已经可以正常启动了
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
解决这个问题还有一个方法,就是配置允许循环依赖,在application.yml文件中添加如下配置
spring:
main:
allow-circular-references: true
在xml文件中的字符串判断
<if test="data != '4'.toString()">
and data > #{data}
</if>
<if test="data == '4'.toString()">
and data = #{data}
</if>