1. package com.itheima.mapper;
  2.  
  3. import com.github.pagehelper.Page;
  4. import com.github.pagehelper.PageHelper;
  5. import com.github.pagehelper.PageInfo;
  6. import com.itheima.domain.User;
  7. import org.apache.ibatis.io.Resources;
  8. import org.apache.ibatis.session.SqlSession;
  9. import org.apache.ibatis.session.SqlSessionFactory;
  10. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  11. import org.junit.Test;
  12.  
  13. import java.io.IOException;
  14. import java.io.InputStream;
  15. import java.util.Arrays;
  16. import java.util.Date;
  17. import java.util.List;
  18.  
  19. public class UserMapperTest {
  20.  
  21. @Test
  22. public void pageHelperTest() throws IOException {
  23. //获取配置
  24. InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
  25. //创建SqlSessionFactory
  26. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
  27. //创建SqlSession
  28. SqlSession sqlSession = sqlSessionFactory.openSession();
  29. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  30.  
  31. //配置分页参数
  32. Page page = PageHelper.startPage(3, 4);
  33.  
  34. //PageHelper只对紧跟着的第一个SQL语句起作用
  35. List<User> byCondition = mapper.findByCondition(new User());
  36.  
  37. //获得分页相关参数
  38. PageInfo<User> userPageInfo = new PageInfo<>(byCondition);
  39.  
  40. //PageInfo实现了toString方法,不用我们自己打印
  41. System.out.println(userPageInfo);
  42.  
  43. System.out.println("总页数=" + userPageInfo.getPages());
  44. System.out.println("总条数=" + userPageInfo.getTotal());
  45. System.out.println("当前页=" + userPageInfo.getPageNum());
  46. System.out.println("页大小=" + userPageInfo.getPageSize());
  47. System.out.println("当前页条数=" + userPageInfo.getSize());
  48. System.out.println("是否是首页=" + userPageInfo.isIsFirstPage());
  49. System.out.println("是否是末页=" + userPageInfo.isIsLastPage());
  50. System.out.println("是否有上一页=" + userPageInfo.isHasPreviousPage());
  51. System.out.println("是否有下一页=" + userPageInfo.isHasNextPage());
  52. System.out.println("上一页=" + userPageInfo.getPrePage());
  53. System.out.println("下一页=" + userPageInfo.getNextPage());
  54. System.out.println("首页=" + userPageInfo.getFirstPage());
  55. System.out.println("末页=" + userPageInfo.getLastPage());
  56. //默认显示几个页码
  57. System.out.println("导航页码数=" + userPageInfo.getNavigatePages());
  58. //页码的数组
  59. System.out.println("所有导航页码=" + Arrays.toString(userPageInfo.getNavigatepageNums()));
  60.  
  61. // List<User> userList = mapper.findAll();
  62. // System.out.println(userList);//传回的并不是Collection中List的实现类,而是自定义List实现类,toString方法处理有区别
  63. // for (User user : userList) {
  64. // System.out.println(user);
  65. // }
  66. // userList.forEach(System.out::println);
  67. sqlSession.close();
  68. }
  69.  
  70. @Test
  71. public void saveTest() throws IOException {
  72. //获取配置
  73. InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
  74. //创建SqlSessionFactory
  75. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
  76. //创建SqlSession
  77. SqlSession sqlSession = sqlSessionFactory.openSession();
  78. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  79. //准备User
  80. User user = new User();
  81. user.setUsername("xxx");
  82. user.setPassword("123");
  83. user.setBirthday(new Date());
  84.  
  85. int rows = mapper.save(user);
  86. sqlSession.commit();
  87. System.out.println(rows);
  88.  
  89. sqlSession.close();
  90. }
  91.  
  92. @Test
  93. public void findByConditionTest() throws IOException {
  94. //获取配置
  95. InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
  96. //创建SqlSessionFactory
  97. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
  98. //创建SqlSession
  99. SqlSession sqlSession = sqlSessionFactory.openSession();
  100. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  101.  
  102. //条件
  103. User user = new User();
  104. user.setId(1);
  105. // user.setUsername("lisi");
  106. // user.setPassword("123");
  107.  
  108. List<User> userList = mapper.findByCondition(user);
  109. System.out.println(userList);
  110.  
  111. sqlSession.close();
  112. }
  113.  
  114. @Test
  115. public void findByIdsTest() throws IOException {
  116. //获取配置
  117. InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
  118. //创建SqlSessionFactory
  119. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
  120. //创建SqlSession
  121. SqlSession sqlSession = sqlSessionFactory.openSession();
  122. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  123.  
  124. // int[] ids = {1,2,3};
  125. Integer[] ids = {1,2,3};
  126. List<User> userList = mapper.findByIds(ids);
  127. System.out.println(userList);
  128.  
  129. sqlSession.close();
  130. }
  131.  
  132. @Test
  133. public void findByIdTest() throws IOException {
  134. //获取配置
  135. InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
  136. //创建SqlSessionFactory
  137. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
  138. //创建SqlSession
  139. SqlSession sqlSession = sqlSessionFactory.openSession();
  140. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  141.  
  142. User user = mapper.findById(1);
  143. System.out.println(user);
  144.  
  145. sqlSession.close();
  146. }
  147.  
  148. @Test
  149. public void findAllTest() throws IOException {
  150. //获取配置
  151. InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
  152. //创建SqlSessionFactory
  153. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
  154. //创建SqlSession
  155. SqlSession sqlSession = sqlSessionFactory.openSession();
  156. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  157.  
  158. List<User> userList = mapper.findAll();
  159. System.out.println(userList);
  160.  
  161. sqlSession.close();
  162. }
  163. }

UserMapperTest

  1. package com.itheima.mapper;
  2.  
  3. import com.itheima.domain.User;
  4.  
  5. import java.util.List;
  6.  
  7. public interface UserMapper {
  8.  
  9. List<User> findByCondition(User condition);
  10.  
  11. List<User> findAll();
  12.  
  13. // List<User> findByIds(int[] ids);
  14. List<User> findByIds(Integer[] ids);
  15.  
  16. User findById(int id);
  17.  
  18. //如果不写返回值,则调用方法不会有影响行数返回值
  19. int save(User user);
  20. }

UserMapper

  1. package com.itheima.handler;
  2.  
  3. import org.apache.ibatis.type.BaseTypeHandler;
  4. import org.apache.ibatis.type.JdbcType;
  5.  
  6. import java.sql.CallableStatement;
  7. import java.sql.PreparedStatement;
  8. import java.sql.ResultSet;
  9. import java.sql.SQLException;
  10. import java.util.Date;
  11.  
  12. public class DateTypeHandler extends BaseTypeHandler<Date> {
  13. @Override
  14. public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
  15. preparedStatement.setLong(i, date.getTime());
  16. }
  17.  
  18. @Override
  19. public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
  20. return new Date(resultSet.getLong(s));
  21. }
  22.  
  23. @Override
  24. public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
  25. return new Date(resultSet.getLong(i));
  26. }
  27.  
  28. @Override
  29. public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
  30. return new Date(callableStatement.getLong(i));
  31. }
  32. }

DateTypeHandler

  1. package com.itheima.domain;
  2.  
  3. import java.util.Date;
  4.  
  5. /*
  6. CREATE TABLE `user` (
  7. `id` int(11) NOT NULL AUTO_INCREMENT,
  8. `username` varchar(50) DEFAULT NULL,
  9. `password` varchar(50) DEFAULT NULL,
  10. `birthday` bigint(20) DEFAULT NULL,
  11. PRIMARY KEY (`id`)
  12. ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
  13. */
  14. public class User {
  15. private int id;
  16. private String username;
  17. private String password;
  18. private Date birthday;
  19.  
  20. public User() {
  21. }
  22.  
  23. public int getId() {
  24. return id;
  25. }
  26.  
  27. public void setId(int id) {
  28. this.id = id;
  29. }
  30.  
  31. public String getUsername() {
  32. return username;
  33. }
  34.  
  35. public void setUsername(String username) {
  36. this.username = username;
  37. }
  38.  
  39. public String getPassword() {
  40. return password;
  41. }
  42.  
  43. public void setPassword(String password) {
  44. this.password = password;
  45. }
  46.  
  47. public Date getBirthday() {
  48. return birthday;
  49. }
  50.  
  51. public void setBirthday(Date birthday) {
  52. this.birthday = birthday;
  53. }
  54.  
  55. @Override
  56. public String toString() {
  57. return "User{" +
  58. "id=" + id +
  59. ", username='" + username + '\'' +
  60. ", password='" + password + '\'' +
  61. ", birthday=" + birthday +
  62. '}';
  63. }
  64. }

User

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6.  
  7. <!--外部的资源文件-->
  8. <properties resource="jdbc.properties"></properties>
  9.  
  10. <!--别名-->
  11. <typeAliases>
  12. <typeAlias type="com.itheima.domain.User" alias="user"></typeAlias>
  13. </typeAliases>
  14.  
  15. <!--注册类型处理器-->
  16. <typeHandlers>
  17. <typeHandler handler="com.itheima.handler.DateTypeHandler" ></typeHandler>
  18. </typeHandlers>
  19.  
  20. <!--配置分页助手插件-->
  21. <plugins>
  22. <plugin interceptor="com.github.pagehelper.PageHelper">
  23. <property name="dialect" value="mysql"></property>
  24. </plugin>
  25. </plugins>
  26.  
  27. <environments default="development">
  28. <environment id="development">
  29. <transactionManager type="JDBC"></transactionManager>
  30. <dataSource type="POOLED">
  31. <property name="driver" value="${jdbc.driver}"></property>
  32. <property name="url" value="${jdbc.url}"></property>
  33. <property name="username" value="${jdbc.username}"></property>
  34. <property name="password" value="${jdbc.password}"></property>
  35. </dataSource>
  36. </environment>
  37. </environments>
  38.  
  39. <mappers>
  40. <mapper resource="com/itheima/mapper/UserMapper.xml"></mapper>
  41. </mappers>
  42. </configuration>

SqlMapConfig.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.itheima.mapper.UserMapper">
  6.  
  7. <insert id="save" parameterType="user">
  8. insert into user(username, password, birthday) values(#{username},#{password},#{birthday})
  9. </insert>
  10.  
  11. <sql id="selectUser">
  12. select * from user
  13. </sql>
  14.  
  15. <select id="findAll" resultType="user">
  16. <include refid="selectUser"></include>
  17. </select>
  18.  
  19. <select id="findById" parameterType="int" resultType="user">
  20. <include refid="selectUser"></include> where id=#{id}
  21. </select>
  22.  
  23. <select id="findByIds" parameterType="int[]" resultType="user">
  24. <include refid="selectUser"></include>
  25. <where>
  26. <foreach collection="array" item="id" open="id in(" separator="," close=")" >
  27. #{id}
  28. </foreach>
  29. </where>
  30. </select>
  31.  
  32. <select id="findByCondition" parameterType="user" resultType="user">
  33. <include refid="selectUser"></include>
  34. <where>
  35. <if test="id!=0">
  36. and id=#{id}
  37. </if>
  38. <if test="username!=null">
  39. and username=#{username}
  40. </if>
  41. <if test="password!=null">
  42. and password=#{password}
  43. </if>
  44. </where>
  45. </select>
  46. </mapper>

UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.itheima</groupId>
  8. <artifactId>mybatis-day02</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>war</packaging>
  11.  
  12. <name>mybatis-day02 Maven Webapp</name>
  13. <!-- FIXME change it to the project's website -->
  14. <url>http://www.example.com</url>
  15.  
  16. <properties>
  17. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  18. <maven.compiler.source>1.8</maven.compiler.source>
  19. <maven.compiler.target>1.8</maven.compiler.target>
  20. </properties>
  21.  
  22. <dependencies>
  23. <!--junit-->
  24. <dependency>
  25. <groupId>junit</groupId>
  26. <artifactId>junit</artifactId>
  27. <version>4.11</version>
  28. <scope>test</scope>
  29. </dependency>
  30. <!--mybatis-->
  31. <dependency>
  32. <groupId>org.mybatis</groupId>
  33. <artifactId>mybatis</artifactId>
  34. <version>3.4.6</version>
  35. </dependency>
  36. <!--mysql-->
  37. <dependency>
  38. <groupId>mysql</groupId>
  39. <artifactId>mysql-connector-java</artifactId>
  40. <version>5.1.37</version>
  41. </dependency>
  42. <!--log4j-->
  43. <dependency>
  44. <groupId>log4j</groupId>
  45. <artifactId>log4j</artifactId>
  46. <version>1.2.17</version>
  47. </dependency>
  48. <!--pagehelper-->
  49. <dependency>
  50. <groupId>com.github.pagehelper</groupId>
  51. <artifactId>pagehelper</artifactId>
  52. <version>3.7.5</version>
  53. </dependency>
  54. <dependency>
  55. <groupId>com.github.jsqlparser</groupId>
  56. <artifactId>jsqlparser</artifactId>
  57. <version>0.9.1</version>
  58. </dependency>
  59. </dependencies>
  60.  
  61. <build>
  62. <finalName>mybatis-day02</finalName>
  63. <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
  64. <plugins>
  65. <plugin>
  66. <artifactId>maven-clean-plugin</artifactId>
  67. <version>3.1.0</version>
  68. </plugin>
  69. <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
  70. <plugin>
  71. <artifactId>maven-resources-plugin</artifactId>
  72. <version>3.0.2</version>
  73. </plugin>
  74. <plugin>
  75. <artifactId>maven-compiler-plugin</artifactId>
  76. <version>3.8.0</version>
  77. </plugin>
  78. <plugin>
  79. <artifactId>maven-surefire-plugin</artifactId>
  80. <version>2.22.1</version>
  81. </plugin>
  82. <plugin>
  83. <artifactId>maven-war-plugin</artifactId>
  84. <version>3.2.2</version>
  85. </plugin>
  86. <plugin>
  87. <artifactId>maven-install-plugin</artifactId>
  88. <version>2.5.2</version>
  89. </plugin>
  90. <plugin>
  91. <artifactId>maven-deploy-plugin</artifactId>
  92. <version>2.8.2</version>
  93. </plugin>
  94. </plugins>
  95. </pluginManagement>
  96. </build>
  97. </project>

pom.xml

  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3307/test
  3. jdbc.username=root
  4. jdbc.password=root

jdbc.properties

  1. ### direct log messages to stdout ###
  2. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  3. log4j.appender.stdout.Target=System.err
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
  6.  
  7. ### direct messages to file mylog.log ###
  8. log4j.appender.file=org.apache.log4j.FileAppender
  9. log4j.appender.file.File=c:/mylog.log
  10. log4j.appender.file.layout=org.apache.log4j.PatternLayout
  11. log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
  12.  
  13. ### set log levels - for more verbose logging change 'info' to 'debug' ###
  14.  
  15. log4j.rootLogger=debug, stdout

log4j.properties

黑马MyBatisday2 MyBatis Dao层实现 接口代理实现&传统实现 动态SQL和SQL抽取 自定义类型处理 分页插件PageHelper的更多相关文章

  1. Mybatis的dao层实现 接口代理方式实现规范+plugins-PageHelper

    Mybatis的dao层实现 接口代理方式实现规范 Mapper接口实现时的相关规范: Mapper接口开发只需要程序员编写Mapper接口而不用具体实现其代码(相当于我们写的Imp实现类) Mapp ...

  2. MyBatis开发Dao层的两种方式(Mapper动态代理方式)

    MyBatis开发原始Dao层请阅读我的上一篇博客:MyBatis开发Dao层的两种方式(原始Dao层开发) 接上一篇博客继续介绍MyBatis开发Dao层的第二种方式:Mapper动态代理方式 Ma ...

  3. MyBatis Dao层的编写

    传统的dao层编写 以前编写dao层,先新建一个包com.chy.dao,再写接口StudentDao: public interface StudentDao { public void inser ...

  4. MyBatis dao层 方法传参

    MyBatis dao层 方法传参有三种方法. 1. 以下标的方法获取参数. <update id="insertSuccessKilled">       INSER ...

  5. SpringBoot+MyBatis多数据源使用分页插件PageHelper

    之前只用过单数据源下的分页插件,而且几乎不用配置.一个静态方法就能搞定. PageHelper.startPage(pageNum, pageSize); 后来使用了多数据源(不同的数据库),Page ...

  6. mybatis分页插件PageHelper的使用(转)

    Mybatis 的分页插件PageHelper-4.1.1的使用 Mybatis 的分页插件 PageHelper 项目地址:http://git.oschina.net/free/Mybatis_P ...

  7. Mybatis分页插件PageHelper的配置和使用方法

     Mybatis分页插件PageHelper的配置和使用方法 前言 在web开发过程中涉及到表格时,例如dataTable,就会产生分页的需求,通常我们将分页方式分为两种:前端分页和后端分页. 前端分 ...

  8. SpringBoot集成MyBatis的分页插件 PageHelper

    首先说说MyBatis框架的PageHelper插件吧,它是一个非常好用的分页插件,通常我们的项目中如果集成了MyBatis的话,几乎都会用到它,因为分页的业务逻辑说复杂也不复杂,但是有插件我们何乐而 ...

  9. (转)淘淘商城系列——MyBatis分页插件(PageHelper)的使用以及商品列表展示

    http://blog.csdn.net/yerenyuan_pku/article/details/72774381 上文我们实现了展示后台页面的功能,而本文我们实现的主要功能是展示商品列表,大家要 ...

随机推荐

  1. iOS数据持久化存储之属性列表

    属性列表(plist) iOS提供了一种plist格式的文件(属性列表)用于存储轻量级的数据,属性列表是一种XML格式的文件,拓展名为plist.如果对象是NSString.NSDictionary. ...

  2. jquery 3D分页翻转滑块

    jquery 3D分页翻转滑块,jquery分页,jquery插件,jquery,3D翻转,css3分页,360度旋转,网页特效代码3D分页翻转滑块是一款使用网格样式与滑块效果分页的特效.

  3. ios审核过程十大常见被拒问题

    欢迎加入ios马甲包经验交流群,群聊号码:744520623 2018年伊始,苹果并没有因为新年的气氛而对CP们“网开一面”.频繁锁榜.调整排名规则以及关键词覆盖算法……不断抛出的大动作,让CP们叫苦 ...

  4. 第三届蓝桥杯预赛c++b组

    1.微生物增值 假设有两种微生物 X 和 Y     X出生后每隔3分钟分裂一次(数目加倍),Y出生后每隔2分钟分裂一次(数目加倍).     一个新出生的X,半分钟之后吃掉1个Y,并且,从此开始,每 ...

  5. find命令的基础用法以及按文件修改时间查找文件

    一般文件查找方法: find 命令学好是一件很有趣的事情,也可以帮你在查找系统文件的时候事倍功半,还可以与正则表达式结合使用,功能强大,是一个很好的查找工具.可以整体提高你的系统管理能力. 基础用法 ...

  6. 【LeetCode】Maximum Product Subarray 求连续子数组使其乘积最大

    Add Date 2014-09-23 Maximum Product Subarray Find the contiguous subarray within an array (containin ...

  7. BZOJ-3881:Divljak (AC自动机+DFS序+树链求并+树状数组)

    Alice有n个字符串S_1,S_2...S_n,Bob有一个字符串集合T,一开始集合是空的. 接下来会发生q个操作,操作有两种形式: “1 P”,Bob往自己的集合里添加了一个字符串P. “2 x” ...

  8. BZOJ1146:[CTSC2008]网络管理

    浅谈树状数组与线段树:https://www.cnblogs.com/AKMer/p/9946944.html 题目传送门:https://www.lydsy.com/JudgeOnline/prob ...

  9. MFC ListBox 设置水平长度

    在*.rc资源 设置可以水平滚动, 垂直滚动 但是 水平滚动无效,水平方向 一直无法显示 完整 设置代码如下 m_listBox.SetHorizontalExtent(2000); m_listBo ...

  10. MFC获取数据的方式

    假设输入框ID是:ID_NUMBER1,ID_NUMBER2,ID_NUMBER3. 获取数据的方式是: int number1,number2,number3; number1 = GetDlgIt ...