package com.itheima.mapper;

 import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test; import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List; public class UserMapperTest { @Test
public void pageHelperTest() throws IOException {
//获取配置
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class); //配置分页参数
Page page = PageHelper.startPage(3, 4); //PageHelper只对紧跟着的第一个SQL语句起作用
List<User> byCondition = mapper.findByCondition(new User()); //获得分页相关参数
PageInfo<User> userPageInfo = new PageInfo<>(byCondition); //PageInfo实现了toString方法,不用我们自己打印
System.out.println(userPageInfo); System.out.println("总页数=" + userPageInfo.getPages());
System.out.println("总条数=" + userPageInfo.getTotal());
System.out.println("当前页=" + userPageInfo.getPageNum());
System.out.println("页大小=" + userPageInfo.getPageSize());
System.out.println("当前页条数=" + userPageInfo.getSize());
System.out.println("是否是首页=" + userPageInfo.isIsFirstPage());
System.out.println("是否是末页=" + userPageInfo.isIsLastPage());
System.out.println("是否有上一页=" + userPageInfo.isHasPreviousPage());
System.out.println("是否有下一页=" + userPageInfo.isHasNextPage());
System.out.println("上一页=" + userPageInfo.getPrePage());
System.out.println("下一页=" + userPageInfo.getNextPage());
System.out.println("首页=" + userPageInfo.getFirstPage());
System.out.println("末页=" + userPageInfo.getLastPage());
//默认显示几个页码
System.out.println("导航页码数=" + userPageInfo.getNavigatePages());
//页码的数组
System.out.println("所有导航页码=" + Arrays.toString(userPageInfo.getNavigatepageNums())); // List<User> userList = mapper.findAll();
// System.out.println(userList);//传回的并不是Collection中List的实现类,而是自定义List实现类,toString方法处理有区别
// for (User user : userList) {
// System.out.println(user);
// }
// userList.forEach(System.out::println);
sqlSession.close();
} @Test
public void saveTest() throws IOException {
//获取配置
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//准备User
User user = new User();
user.setUsername("xxx");
user.setPassword("123");
user.setBirthday(new Date()); int rows = mapper.save(user);
sqlSession.commit();
System.out.println(rows); sqlSession.close();
} @Test
public void findByConditionTest() throws IOException {
//获取配置
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class); //条件
User user = new User();
user.setId(1);
// user.setUsername("lisi");
// user.setPassword("123"); List<User> userList = mapper.findByCondition(user);
System.out.println(userList); sqlSession.close();
} @Test
public void findByIdsTest() throws IOException {
//获取配置
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class); // int[] ids = {1,2,3};
Integer[] ids = {1,2,3};
List<User> userList = mapper.findByIds(ids);
System.out.println(userList); sqlSession.close();
} @Test
public void findByIdTest() throws IOException {
//获取配置
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.findById(1);
System.out.println(user); sqlSession.close();
} @Test
public void findAllTest() throws IOException {
//获取配置
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.findAll();
System.out.println(userList); sqlSession.close();
}
}

UserMapperTest

 package com.itheima.mapper;

 import com.itheima.domain.User;

 import java.util.List;

 public interface UserMapper {

     List<User> findByCondition(User condition);

     List<User> findAll();

 //    List<User> findByIds(int[] ids);
List<User> findByIds(Integer[] ids); User findById(int id); //如果不写返回值,则调用方法不会有影响行数返回值
int save(User user);
}

UserMapper

 package com.itheima.handler;

 import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType; import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date; public class DateTypeHandler extends BaseTypeHandler<Date> {
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
preparedStatement.setLong(i, date.getTime());
} @Override
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
return new Date(resultSet.getLong(s));
} @Override
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
return new Date(resultSet.getLong(i));
} @Override
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
return new Date(callableStatement.getLong(i));
}
}

DateTypeHandler

 package com.itheima.domain;

 import java.util.Date;

 /*
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`birthday` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
*/
public class User {
private int id;
private String username;
private String password;
private Date birthday; public User() {
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
'}';
}
}

User

 <?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 resource="jdbc.properties"></properties> <!--别名-->
<typeAliases>
<typeAlias type="com.itheima.domain.User" alias="user"></typeAlias>
</typeAliases> <!--注册类型处理器-->
<typeHandlers>
<typeHandler handler="com.itheima.handler.DateTypeHandler" ></typeHandler>
</typeHandlers> <!--配置分页助手插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"></property>
</plugin>
</plugins> <environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="com/itheima/mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>

SqlMapConfig.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.itheima.mapper.UserMapper"> <insert id="save" parameterType="user">
insert into user(username, password, birthday) values(#{username},#{password},#{birthday})
</insert> <sql id="selectUser">
select * from user
</sql> <select id="findAll" resultType="user">
<include refid="selectUser"></include>
</select> <select id="findById" parameterType="int" resultType="user">
<include refid="selectUser"></include> where id=#{id}
</select> <select id="findByIds" parameterType="int[]" resultType="user">
<include refid="selectUser"></include>
<where>
<foreach collection="array" item="id" open="id in(" separator="," close=")" >
#{id}
</foreach>
</where>
</select> <select id="findByCondition" parameterType="user" resultType="user">
<include refid="selectUser"></include>
<where>
<if test="id!=0">
and id=#{id}
</if>
<if test="username!=null">
and username=#{username}
</if>
<if test="password!=null">
and password=#{password}
</if>
</where>
</select>
</mapper>

UserMapper.xml

 <?xml version="1.0" encoding="UTF-8"?>

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.itheima</groupId>
<artifactId>mybatis-day02</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging> <name>mybatis-day02 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties> <dependencies>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--pagehelper-->
<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>
</dependencies> <build>
<finalName>mybatis-day02</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

pom.xml

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

jdbc.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### 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. debian7配置

    输入法: apt-get install ibus ibus-pinyin 并执行ibus-setup进行配置,首选项->输入法->中文,然后按添加按钮即可. 软件开发基本软件:apt-g ...

  2. 使用pidof/kill组合命令,变相解决mediaserver内存泄漏【转】

    本文转载自:https://blog.csdn.net/lj402159806/article/details/78950384 在5.1系统下mediaserver有内存泄漏的问题,原因在于使用ca ...

  3. c# XML-Object对象 序列化-反序列化

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Tex ...

  4. Contiki 2.7 Makefile 文件(一)

    一.主控Makefile 这里以hello-world例子为主线,从其工程Makefile开始,解析整个build过程.

  5. Linux三种网络-vmware三种网络模式

    Host-Only 桥接 NAT VMware虚拟机三种联网方法及原理 一.Brigde——桥接:默认使用VMnet0 1.原理: Bridge 桥"就是一个主机,这个机器拥有两块网卡,分别 ...

  6. python的上下文管理器

    直接上代码: f = open('123.txt','w') try: f.write('hello world') except Exception: pass finally: f.close() ...

  7. BZOJ1067&P2471 [SCOI2007]降雨量[线段树裸题+细节注意]

    dlntqlwsl 很裸的一道线段树题,被硬生生刷成了紫题..可能因为细节问题吧,我也栽了一次WA50分.不过这个隐藏条件真的对本菜鸡来说不易发现啊. 未知的年份连续的就看成一个就好了,把年份都离散化 ...

  8. 「NOIP2017」「LuoguP3952」 时间复杂度(模拟,栈

    题目描述 小明正在学习一种新的编程语言 A++,刚学会循环语句的他激动地写了好多程序并 给出了他自己算出的时间复杂度,可他的编程老师实在不想一个一个检查小明的程序, 于是你的机会来啦!下面请你编写程序 ...

  9. ACM学习历程—ZOJ3878 Convert QWERTY to Dvorak(Hash && 模拟)

    Description Edward, a poor copy typist, is a user of the Dvorak Layout. But now he has only a QWERTY ...

  10. docker的操作

    查询容器 docker ps  只能查询到正在运行的docker镜像: 如果添加上-a的选项,则会显示所有的(包括已经exit,未启动)的容器 基于一个镜像来构建(run)容器,并启动 docker ...