整合一直出问题,一气之下就把mybatis的东西又看了一遍,争取把里面的配置都做到心中有数,为什么要这么配置,这么配置有什么左右,这个必须弄清楚才行。以下是操作步骤:
一、注解写sql版:
1、配置pom.xml
//druid依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
//这个包在mybatis框架之上提供了很多工具,为了简化开发,如果要使用还需要自定义一个接口
//这个之后再说
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
</dependency>
//一个用来分页的工具
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
//mybatis
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
//mysql-connector
<!-- Database Begin -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Database End -->
2、配置application.yml,主要是配置数据库连接,替换成druid数据源,还有配置数据库连接信息
这一段对应mybatis框架中的SqlMapConfig.xml中的数据库连接配置
datasource:
druid:
url: jdbc:mysql://localhost:3306/数据库名称?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: xxxx
initial-size: 1
min-idle: 1
max-active: 20
test-on-borrow: true
# MySQL 8.x: com.mysql.cj.jdbc.Driver
driver-class-name: com.mysql.jdbc.Driver
这一步可以选择在application.yml中配置,当然也可以自己写xxxconfiguration配置类
3、配置applicaton.yml,配置mybatis的相关信息
mybatis:
type-aliases-package: com.yamanda.xxxxx.pojo //pojo包所在路径
这是配置别名,对应mybatis框架中的resultType和parameterType类型,如果不写这个的话,实体类只能写全路径,配置这个之后就可以用别名来替代全路径
4、创建mapper包,里面写xxxmapper接口,里面写方法,可以使用@Select等注解在方法上面写sql语句
xxxmapper接口上面写上@Mapper注解,也可以在主启动类上协商@MapperScan(basePackages = {"mapper包所在路径"})来替代
5、测试即可。
二、xml写sql版
如果使用xml写sql,则注意事项就比较多了,步骤如下
1、pom.xml同上
2、application.yml中关于数据库的部分同上
3、application.yml关于mybatis的配置
mybatis:
//配置实体类别名
# type-aliases-package: com.yamanda.pojo包所在路径
//这个配置主要是当mapper.xml与mapper不在一个路径下的时候配置,如果放在同一路径下,这个也不用配置
# mapper-locations: classpath:mapper/*.xml
//这个是mybatis的核心配置
config-location: classpath:mapper/SqlMapConfig.xml
4、在resource下创建mapper包,然后创建SqlMapConfig.xml文件,内容如下
<?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>
//配置别名,如果上面没配置,这里配置效果相同
<typeAliases>
<package name="com.yamanda.pojo包路径"/>
</typeAliases>
//核心配置文件中配置子配置文件的路径信息,一般和xxxMapper接口文件放在同一路径下,名字也相同
<mappers>
<mapper resource="com/yamanda/xxxMapper.xml所在路径"/>
</mappers>
</configuration>
5、在xxxMapper接口同一路径下创建xxxMapper.xml文件,内容就是写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="xxxMapper接口文件的refrence信息">
<select id="接口中的方法名" parameterType="传入参数">
具体的sql
</select>
</mapper>
6、在xxxMapper接口上面写@Mapper或者在主启动类上写@MapperScan(basePackages={""})即可