springboot整合MySQL数据库(MyBatis + 分页配置)
一、POM文件添加依赖
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--mybatis分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>
<!--jdbc-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
二、创建项目结构
|- src
|- main
|- cn.roylion.demo
|- domain //实体类 放置javaBean
|- controller //控制层 放置controller类
|- service //业务层 放置service类
|- mapper //数据持久层 放置mapper接口
|- resources
|- mybatis //放置mybatis配置文件 和 mapper xml文件
|- mappers //放置mapper xml文件
三、yml配置文件
datasource参数
spring.datasource.url 指定JDBC URL.
spring.datasource.username 指定数据源用户名
spring.datasource.password 指定数据源密码
mybatis参数
mybatis.type-aliases-package: com.example.demo.entity 别名包
mybatis.config-location: classpath:/mybatis/mybatis-config.xml 配置文件所在路径
mybatis.mapper-locations: classpath:/mybatis/mappers/*.xml 配置mapper配置文件所在路径
参考建议: xixicat SpringBoot配置属性之DataSource
四、mybatis-config.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>
<settings>
<!-- 开启驼峰自动映射 -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
<plugins>
<!--mybatis分页插件-->
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
<property name="offsetAsPageNum" value="false"/>
<property name="rowBoundsWithCount" value="false"/>
<property name="pageSizeZero" value="true"/>
<property name="reasonable" value="false"/>
<property name="supportMethodsArguments" value="false"/>
<property name="returnPageInfo" value="none"/>
</plugin>
</plugins>
</configuration>
五、spring启动类增加Mapper扫描
@MapperScan("cn.roylion.demo.mapper")
或 Mapper接口添加@Mapper注解
六、Mapper接口
public interface UserMapper {
List<User> findAll();
}
七、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="cn.roylion.demo.mapper.UserMapper"> //与Mapper接口对应
<select id="findAll" resultType="user">
SELECT * FROM user ORDER BY id ASC
</select>
</mapper>
八、MyBatis实现分页
在service层中调用
int page = 1;
int size = 5;
PageHelper.startPage(page,size); //只生效一次。做两次sql查询,总数查询一次,分页查询一次
List<User> users = userMapper.findAll();
PageInfo<User> pageInfo = new PageInfo<User>(users);
参考建议: xixicat SpringBoot集成mybatis