1:导入坐标
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.7.5</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9.1</version>
</dependency>
2:jdbc.properties配置相关参数
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jdbc1?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
jdbc.username=root
jdbc.password=010429
3:配置UsersMapper.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.xiaoze.mappers.UsersMapper">
<select id="findByCondition" resultType="users">
select * from users
</select>
</mapper>
4: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>
<!-- 通过properties标签加载外部文件-->
<properties resource="jdbc.properties"></properties>
<!-- 自定义别名-->
<typeAliases >
<typeAlias type="com.xiaoze.domain.Users" alias="users"></typeAlias>
</typeAliases>
<!-- 配置分页助手插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
<environments default="development">
<!--配置mysql的环境,注意,default中的属性,与下边environment中id的属性是一样的-->
<environment id="development">
<!--配置事务的类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据源,也叫作连接池-->
<dataSource type="POOLED">
<!--配置连接数据库的四个基本信息-->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
<mappers>
<!--指定文件的位置,要与main中java的文件结构位置相同-->
<mapper resource="UsersMapper.xml"></mapper>
</mappers>
</configuration>
5:配置接口
public interface UsersMapper {
//设置接口
public List<Users> findByCondition() throws IOException;
}
6:实现类方法
public class pluginsHelper {
@Test
public void test1() throws IOException {
//获取核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//获取session工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获取session会话对象
SqlSession sqlSession = build.openSession();
UsersMapper mapper = sqlSession.getMapper(UsersMapper.class);
//设置分页参数,页数+每页显示得条数
PageHelper.startPage(2,3);
List<Users> usersList = mapper.findByCondition();
for (Users users : usersList) {
System.out.println(users);
}
}
}