文章目录
- 1. Mybatis介绍
- 2. Mybatis架构
- 3. Mybatis入门程序
- 4. Mapper动态代理开发持久层方法
- 5. SqlMapConfig.xml配置文件
- 6. Mapper.xml
- 7. Mybatis整合spring
- 8. Mybatis逆向工程(了解)
- 9. 分页插件PageHelper
- 总结
1. Mybatis介绍
- MyBatis是优秀的持久层框架,对jdbc的操作数据库的过程进行封装
- 使开发者只需要关注SQL本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码
- Mybatis通过xml或注解的方式将要执行的各种statement(statement、preparedStatemnt、CallableStatement)配置起来。并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回
2. Mybatis架构
3. Mybatis入门程序
导包
commons-logging-1.1.1.jar
javassist-3.17.1-GA.jar
log4j-1.2.17.jar
log4j-api-2.0-rc1.jar
log4j-core-2.0-rc1.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
asm-3.3.1.jar
cglib-2.2.2.jar在src下创建log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
mybatis默认使用log4j作为输出日志信息。在src下创建SqlMapConfig.xml
SqlMapConfig.xml是mybatis核心配置文件,内容为数据源、事务管理
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!-- 和spring整合后 environments配置将废除 --><environments default="development"><environment id="development"><!-- 使用jdbc事务管理 --><transactionManager type="JDBC" /><!-- 数据库连接池 --><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" /><property name="username" value="root" /><property name="password" value="root" /></dataSource></environment></environments><!--加载配置文件--><mappers><mapper resource="sqlmap/User.xml"/></mappers></configuration>创建pojo类生成set、get方法并创建对应的表在src下的sqlmap目录下创建sql映射文件User.xml
mybatis框架需要加载Mapper.xml映射文件 将user.xml添加在SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- namespace:命名空间,用于隔离sql --><mapper namespace="test"><!-- id:statement的id 或者叫做sql的id--><!-- parameterType:声明输入参数的类型 --><!-- resultType:声明输出结果的类型,应该填写pojo的全路径 --><!-- #{}:输入参数的占位符,相当于jdbc的? --><!--实现根据id查询用户(传入基本值)--><select id="queryUserById" parameterType="int" resultType="cn.mybatis.pojo.User">SELECT * FROM `user` WHERE id = #{id}</select><!-- 如果返回多个结果,mybatis会自动把返回的结果放在list容器中 --><!-- resultType的配置和返回一个结果的配置一样 --><!-- ①方式一:实现根据用户名模糊查询用户 --><select id="queryUserByUsername1" parameterType="string" resultType="cn.itcast.mybatis.pojo.User">SELECT * FROM `user` WHERE username LIKE #{username}</select><!-- ②方式二:实现根据用户名模糊查询用户--><!-- 如果传入的参数是简单数据类型,${}里面必须写value --><select id="queryUserByUsername2" parameterType="string" resultType="cn.itcast.mybatis.pojo.User">SELECT * FROM `user` WHERE username LIKE '%${value}%'</select><!-- 实现添加用户(传入对象) --><insert id="saveUser" parameterType="cn.itcast.mybatis.pojo.User">INSERT INTO `user`(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})</insert> <!-- mysql自增主键返回--><insert id="saveUser" parameterType="cn.mybatis.pojo.User"><!-- selectKey 标签实现主键返回 --><!-- keyColumn:主键对应的表中的哪一列 --><!-- keyProperty:主键对应的pojo中的哪一个属性 --><!-- order:设置在执行insert语句前执行查询id的sql,在执行insert语句之后执行查询id的sql --><!-- resultType:设置返回的id的类型 --><!-- LAST_INSERT_ID():是mysql的函数,返回auto_increment自增列新记录id值--><selectKey keyColumn="id" keyProperty="id" order="AFTER" resultType="int">SELECT LAST_INSERT_ID()</selectKey>INSERT INTO `user`(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})</insert><!--mysql uuid实现主键返回 注意这里使用的order是“BEFORE”--><selectKey keyColumn="id" keyProperty="id" order="BEFORE" resultType="string">SELECT LAST_INSERT_ID()</selectKey>INSERT INTO `user`(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})</insert><!--修改用户(传入对象)--><update id="updateUserById" parameterType="cn.mybatis.pojo.User">UPDATE `user` SET username = #{username} WHERE id = #{id}</update> <!-- 删除用户 --><delete id="deleteUserById" parameterType="int">delete from user where id=#{id}</delete>
</mapper>测试程序:
1. 创建SqlSessionFactoryBuilder对象
2. 加载SqlMapConfig.xml配置文件
3. 创建SqlSessionFactory对象
4. 创建SqlSession对象
5. 执行SqlSession对象执行查询,获取结果User
6. 打印结果
7. 释放资源public class MybatisTest {private SqlSessionFactory sqlSessionFactory = null;@Beforepublic void init() throws Exception {SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);}@Testpublic void testQueryUserById() throws Exception {SqlSession sqlSession = sqlSessionFactory.openSession();Object user = sqlSession.selectOne("queryUserById", 1);sqlSession.close();}@Testpublic void testQueryUserByUsername1() throws Exception {SqlSession sqlSession = sqlSessionFactory.openSession();List<Object> list = sqlSession.selectList("queryUserByUsername1", "%王%");for (Object user : list) {System.out.println(user);}sqlSession.close();}@Testpublic void testQueryUserByUsername2() throws Exception {SqlSession sqlSession = sqlSessionFactory.openSession();List<Object> list = sqlSession.selectList("queryUserByUsername2", "王");for (Object user : list) {System.out.println(user);}sqlSession.close();} @Testpublic void testSaveUser() {SqlSession sqlSession = sqlSessionFactory.openSession();User user = new User();user.setUsername("张飞");user.setSex("1");user.setBirthday(new Date());user.setAddress("蜀国");sqlSession.insert("saveUser", user);System.out.println(user);sqlSession.commit();sqlSession.close();}@Testpublic void testUpdateUserById() {SqlSession sqlSession = sqlSessionFactory.openSession();User user = new User();user.setId(26);user.setUsername("关羽");user.setSex("1");user.setBirthday(new Date());user.setAddress("蜀国");sqlSession.update("updateUserById", user);sqlSession.commit();sqlSession.close();}@Testpublic void testDeleteUserById() {SqlSession sqlSession = sqlSessionFactory.openSession();sqlSession.delete("deleteUserById", 48);sqlSession.commit();sqlSession.close();}
}
4. Mapper动态代理开发持久层方法
Mapper接口开发方法只需编写Mapper接口(Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象遵循以下规范:1、Mapper.xml文件中的namespace与mapper接口的完整类名相同。2、Mapper接口方法名和Mapper.xml中定义的每个statement的id相同 3、Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同4、Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同Mapper.xml(映射文件)必须满足规范<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- namespace:命名空间,用于隔离sql 还有一个很重要的作用,使用动态代理开发DAO,1. namespace必须和Mapper接口类路径一致 --><mapper namespace="cn.itcast.mybatis.mapper.UserMapper"><!-- 根据用户id查询用户 --><!-- 2. id必须和Mapper接口方法名一致 --><!-- 3. parameterType必须和接口方法参数类型一致 --><!-- 4. resultType必须和接口方法返回值类型一致 --><select id="queryUserById" parameterType="int" resultType="cn.itcast.mybatis.pojo.User">select * from user where id = #{id}</select><!-- 根据用户名查询用户 --><select id="queryUserByUsername" parameterType="string" resultType="cn.itcast.mybatis.pojo.User">select * from user where username like '%${value}%'</select></mapper>UserMapper(接口文件)public interface UserMapper {User queryUserById(int id);List<User> queryUserByUsername(String username);}SqlMapConfig.xml文件(一样)测试public class UserMapperTest {private SqlSessionFactory sqlSessionFactory;@Beforepublic void init() throws Exception {SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);}@Testpublic void testQueryUserById() {SqlSession sqlSession = this.sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);User user = userMapper.queryUserById(1);System.out.println(user);sqlSession.close();}@Testpublic void testQueryUserByUsername() {SqlSession sqlSession = this.sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);List<User> list = userMapper.queryUserByUsername("张");for (User user : list) {System.out.println(user);}sqlSession.close();}}}
5. SqlMapConfig.xml配置文件
SqlMapConfig.xml中配置的内容和顺序如下:properties(属性)settings(全局配置参数)typeAliases(类型别名)typeHandlers(类型处理器)objectFactory(对象工厂)plugins(插件)environments(环境集合属性对象)environment(环境子属性对象)transactionManager(事务管理)dataSource(数据源)mappers(映射器)properties(属性)SqlMapConfig.xml可以引用java属性文件中的配置信息如下:在src下定义db.properties文件jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8jdbc.username=rootjdbc.password=rootMyBatis加载属性顺序:在properties元素中resource或 url 加载的属性,它会覆盖已读取的同名属性。 <configuration><!-- 是用resource属性加载外部配置文件 --><properties resource="db.properties"><!-- 在properties内部用property定义属性 --><!-- 如果外部配置文件有该属性,则内部定义属性被外部属性覆盖 --><property name="jdbc.username" value="root123" /><property name="jdbc.password" value="root123" /> </properties><typeAliases><!-- 单个别名定义 在mapper.xml配置文件中,就可以使用设置的别名user了,别名大小写不敏感--><typeAlias alias="user" type="cn.itcast.mybatis.pojo.User" /><!-- 批量别名定义,扫描整个包下的类,别名为类名(大小写不敏感) --><package name="cn.itcast.mybatis.pojo" /><package name="其它包" /></typeAliases><!-- 和spring整合后 environments配置将废除 --><environments default="development"><environment id="development"><!-- 使用jdbc事务管理 --><transactionManager type="JDBC" /><!-- 数据库连接池 --><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><mappers><!-- mappers(映射器)加载Mapper.xml配置文件 --><!-- ①使用相对于类路径的资源(现在的使用方式)原始dao第一种有用--><mapper resource="sqlmap/User.xml" /><!-- ②使用mapper接口类路径--><!-- 要求mapper接口名称和mapper映射文件名称相同,且在同一个目录中 --><!-- <mapper class="cn.mybatis.mapper.UserMapper"/>--><!--③注册指定包下的所有mapper接口--><!--<package name="cn.itcast.mybatis.mapper"/>--><!--要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。--><!--整合spring后用代理方式开发的话,后两者没有用(默认)--> </mappers></configuration>
mybatis支持别名 | 映射的类型 | 别名 | 映射的类型 |
---|---|---|---|
_byte | byte | byte | Byte |
_long | long | long | Long |
_short | short | short | Short |
_int | int | int | Integer |
_integer | int | integer | Integer |
_double | double | double | Double |
_float | float | float | Float |
_boolean | boolean | boolean | Boolean |
string | String | date | Date |
decimal | BigDecimal | bigdecimal | BigDecimal |
map | Map |
6. Mapper.xml
If标签
<!--注意字符串类型的数据需要要做不等于空字符串校验。-->
<select id="queryUserByWhere" parameterType="user" resultType="user">SELECT id, username, birthday, sex, address FROM `user`WHERE 1=1<if test="sex != null and sex != ''">AND sex = #{sex}</if><if test="username != null and username != ''">AND username LIKE'%${username}%'</if>
</select>Where标签
上面的sql还有where 1=1 这样的语句,很麻烦,可以使用where标签进行改造,只能处理前面的and,不能处理后置and改造UserMapper.xml,如下<select id="queryUserByWhere" parameterType="user" resultType="user">SELECT id, username, birthday, sex, address FROM `user`<!-- where标签可以自动添加where,同时处理sql语句中第一个and关键字 --><where><if test="sex != null">AND sex = #{sex}</if><if test="username != null and username != ''">AND username LIKE'%${username}%'</if></where></select>Sql片段
Sql中可将重复的sql提取出来,使用时用include引用即可,达到sql重用的目的
<select id="queryUserByWhere" parameterType="user" resultType="user"><!-- SELECT id, username, birthday, sex, address FROM `user` --><!-- 使用include标签加载sql片段;refid是sql片段id -->SELECT <include refid="userFields" /> FROM `user`
</select><!-- 声明sql片段 如果要使用别的Mapper.xml配置的sql片段,可以在refid前面加上对应的Mapper.xml的namespace
refid="com.junye.userFields"-->
<sql id="userFields">id, username, birthday, sex, address
</sql>foreach标签
向sql传递数组或List,mybatis使用foreach解析
Integer[]→ collection="array"、
List<Integer>→ collection="list"
如果以上两个东西放进类中被包装了,那么用属性名表示
<select id="queryUserByIds" parameterType="queryVo" resultType="user">SELECT * FROM `user`<where><!-- foreach标签,进行遍历 --><!-- collection:遍历的集合,这里是QueryVo的ids属性 --><!-- item:遍历的项目,可以随便写,,但是和后面的#{}里面要一致 --><!-- open:在前面添加的sql片段 --><!-- close:在结尾处添加的sql片段 --><!-- separator:指定遍历的元素之间使用的分隔符 --><foreach collection="ids" item="item" open="id IN (" close=")" separator=",">#{item}</foreach></where>
</select>一对多查询
在UserMapper.xml添加sql,如下:
resultMap,数据库字段与对象字段不一致时使用
<resultMap type="user" id="userOrderResultMap"><id property="id" column="id" /><result property="username" column="username" /><result property="birthday" column="birthday" /><result property="sex" column="sex" /><result property="address" column="address" /><!-- 配置一对多的关系 --><collection property="orders" javaType="list" ofType="order"><!-- 配置主键,是关联Order的唯一标识 --><id property="id" column="oid" /><result property="number" column="number" /><result property="createtime" column="createtime" /><result property="note" column="note" /></collection>
</resultMap>
7. Mybatis整合spring
整合思路
SqlSessionFactory对象应该放到spring容器中作为单例存在
Mapper代理形式中,应该从spring容器中直接获得mapper的代理对象
数据库的连接以及数据库连接池事务管理都交给spring容器来完成。mybatis整合原理
SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>重写getobject方法返回SqlSessionFactory注入到spring中,
而SqlSessionFactoryBean将由开发人员在spring中声明,完美整合整合需要的jar包
spring-core-4.1.3.RELEASE.jar
spring-expression-4.1.3.RELEASE.jar
spring-jdbc-4.1.3.RELEASE.jar
spring-jms-4.1.3.RELEASE.jar
spring-messaging-4.1.3.RELEASE.jar
spring-tx-4.1.3.RELEASE.jar
spring-web-4.1.3.RELEASE.jar
spring-webmvc-4.1.3.RELEASE.jar
aopalliance-1.0.jar
asm-3.3.1.jar
aspectjweaver-1.6.11.jar
cglib-2.2.2.jar
commons-dbcp-1.2.2.jar
commons-logging-1.1.1.jar
commons-pool-1.3.jar
javassist-3.17.1-GA.jar
jstl-1.2.jar
junit-4.9.jar
log4j-1.2.17.jar
log4j-api-2.0-rc1.jar
log4j-core-2.0-rc1.jar
mybatis-3.2.7.jar
mybatis-spring-1.2.2.jar
mysql-connector-java-5.1.7-bin.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
spring-aop-4.1.3.RELEASE.jar
spring-aspects-4.1.3.RELEASE.jar
spring-beans-4.1.3.RELEASE.jar
spring-context-4.1.3.RELEASE.jar
spring-context-support-4.1.3.RELEASE.jar创建工程
sqlmapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- 设置别名 --><typeAliases><!-- 2. 指定扫描包,会把包内所有的类都设置别名,别名的名称就是类名,大小写不敏感 --><package name="cn.itcast.mybatis.pojo" /></typeAliases>
</configuration>applicationContext.xmlSqlSessionFactoryBean属于mybatis-spring这个jar包对于spring来说,mybatis是另外一个架构,需要整合jar包。
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"><context:property-placeholder location="classpath:db.properties" /><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName" value="${jdbc.driver}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><property name="maxActive" value="10" /><property name="maxIdle" value="5" /></bean><!-- 配置SqlSessionFactory --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 配置mybatis核心配置文件 --><property name="configLocation" value="classpath:SqlMapConfig.xml" /><!-- 配置数据源 --><property name="dataSource" ref="dataSource" /></bean>
</beans>
db.properties、log4j.propertiesDao开发(使用Mapper代理开发方式)
编写UserMapper.xml配置文件,如下:<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="cn.itcast.mybatis.mapper.UserMapper"><!-- 根据用户id查询 --><select id="queryUserById" parameterType="int" resultType="user">select * from user where id = #{id}</select></mapper>UserMapper接口实现类
public interface UserMapper {User queryUserById(int id);
}
扫描包形式配置mapper(注意这个自动寻找sqlsession,所以不用注入sqlsession,自动扫描该包下,
不包括子包的所有接口,默认加载该包下的与接口同名的xml文件作为Mapper,也可以在sqlMapper中配置mapper resource以加载其他的Mapper
没找到mapper.xml就报错,可以在sqlMapperConfig.xml配置mapper resource解决当默认和自己配的文件一样的时候,优先加载默认位置的
每个mapper代理对象的id就是类名,首字母小写
<!-- 扫描包方式配置代理 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 配置Mapper接口 --><property name="basePackage" value="cn.mybatis.mapper" />
</bean>
8. Mybatis逆向工程(了解)
生成逆向工程代码找到下图所示的java文件,执行工程main主函数,刷新工程,发现代码生成注意1.逆向工程生成的代码只能做单表查询2.不能在生成的代码上进行扩展,因为如果数据库变更,需要重新使用逆向工程生成代码,原来编写的代码就被覆盖了。3.一张表会生成4个文件使用官方网站的Mapper自动生成工具mybatis-generator-core-1.3.2来生成po类和Mapper映射文件导入逆向工程修改配置文件在generatorConfig.xml中配置Mapper生成的详细信息,1.修改要生成的数据库表2.pojo文件所在包路径3.Mapper所在的包路径<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><context id="testTables" targetRuntime="MyBatis3"><commentGenerator><!-- 是否去除自动生成的注释 true:是 : false:否 --><property name="suppressAllComments" value="true" /></commentGenerator><!--数据库连接的信息:驱动类、连接地址、用户名、密码 --><jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root" password="root"></jdbcConnection><!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver" connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" userId="yycg" password="yycg"> </jdbcConnection> --><!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --><javaTypeResolver><property name="forceBigDecimals" value="false" /></javaTypeResolver><!-- targetProject:生成PO类的位置 --><javaModelGenerator targetPackage="cn.itcast.ssm.po" targetProject=".\src"><!-- enableSubPackages:是否让schema作为包的后缀 --><property name="enableSubPackages" value="false" /><!-- 从数据库返回的值被清理前后的空格 --><property name="trimStrings" value="true" /></javaModelGenerator><!-- targetProject:mapper映射文件生成的位置 --><sqlMapGenerator targetPackage="cn.itcast.ssm.mapper" targetProject=".\src"><!-- enableSubPackages:是否让schema作为包的后缀 --><property name="enableSubPackages" value="false" /></sqlMapGenerator><!-- targetPackage:mapper接口生成的位置 --><javaClientGenerator type="XMLMAPPER" targetPackage="cn.itcast.ssm.mapper" targetProject=".\src"><!-- enableSubPackages:是否让schema作为包的后缀 --><property name="enableSubPackages" value="false" /></javaClientGenerator><!-- 指定数据库表 --><table schema="" tableName="user"></table><table schema="" tableName="order"></table></context></generatorConfiguration>
9. 分页插件PageHelper
目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库分页。把PageHelper依赖的jar包添加到工程中。官方提供的代码对逆向工程支持的不好,使用参考资料中的pagehelper-fix。第二步:在Mybatis配置xml中配置拦截器插件:
<plugins><!-- com.github.pagehelper为PageHelper类所在包名 --><plugin interceptor="com.github.pagehelper.PageHelper"><!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库--> <property name="dialect" value="mysql"/></plugin>
</plugins>第三步:在代码中使用
1、设置分页信息:
//获取第1页,10条内容,默认查询总数count
PageHelper.startPage(1, 10);//紧跟着的第一个select方法会被分页
List<Country> list = countryMapper.selectIf(1);2、取分页信息
//分页后,实际返回的结果list类型是Page<E>,如果想取出分页信息,需要强制转换为Page<E>,
Page<Country> listCountry = (Page<Country>)list;
listCountry.getTotal();3、取分页信息的第二种方法
//获取第1页,10条内容,默认查询总数count
PageHelper.startPage(1, 10);
List<Country> list = countryMapper.selectAll();
//用PageInfo对结果进行包装
PageInfo page = new PageInfo(list);
//测试PageInfo全部属性
//PageInfo包含了非常全面的分页属性
assertEquals(1, page.getPageNum());
assertEquals(10, page.getPageSize());
assertEquals(1, page.getStartRow());
assertEquals(10, page.getEndRow());
assertEquals(183, page.getTotal());
assertEquals(19, page.getPages());
assertEquals(1, page.getFirstPage());
assertEquals(8, page.getLastPage());
assertEquals(true, page.isFirstPage());
assertEquals(false, page.isLastPage());
assertEquals(false, page.isHasPreviousPage());
assertEquals(true, page.isHasNextPage());@Test
public void testPageHelper() throws Exception {//初始化spring容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");//获得Mapper的代理对象TbItemMapper itemMapper = applicationContext.getBean(TbItemMapper.class);//设置分页信息PageHelper.startPage(1, 30);//执行查询TbItemExample example = new TbItemExample();List<TbItem> list = itemMapper.selectByExample(example);//取分页信息PageInfo<TbItem> pageInfo = new PageInfo<>(list);System.out.println(pageInfo.getTotal());System.out.println(pageInfo.getPages());System.out.println(pageInfo.getPageNum());System.out.println(pageInfo.getPageSize());
}
总结
本文介绍了的Mybatis使用,如有问题欢迎私信和评论