黑马MyBatisday2 MyBatis Dao层实现 接口代理实现&传统实现 动态SQL和SQL抽取 自定义类型处理 分页插件PageHelper
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的更多相关文章
- Mybatis的dao层实现 接口代理方式实现规范+plugins-PageHelper
Mybatis的dao层实现 接口代理方式实现规范 Mapper接口实现时的相关规范: Mapper接口开发只需要程序员编写Mapper接口而不用具体实现其代码(相当于我们写的Imp实现类) Mapp ...
- MyBatis开发Dao层的两种方式(Mapper动态代理方式)
MyBatis开发原始Dao层请阅读我的上一篇博客:MyBatis开发Dao层的两种方式(原始Dao层开发) 接上一篇博客继续介绍MyBatis开发Dao层的第二种方式:Mapper动态代理方式 Ma ...
- MyBatis Dao层的编写
传统的dao层编写 以前编写dao层,先新建一个包com.chy.dao,再写接口StudentDao: public interface StudentDao { public void inser ...
- MyBatis dao层 方法传参
MyBatis dao层 方法传参有三种方法. 1. 以下标的方法获取参数. <update id="insertSuccessKilled"> INSER ...
- SpringBoot+MyBatis多数据源使用分页插件PageHelper
之前只用过单数据源下的分页插件,而且几乎不用配置.一个静态方法就能搞定. PageHelper.startPage(pageNum, pageSize); 后来使用了多数据源(不同的数据库),Page ...
- mybatis分页插件PageHelper的使用(转)
Mybatis 的分页插件PageHelper-4.1.1的使用 Mybatis 的分页插件 PageHelper 项目地址:http://git.oschina.net/free/Mybatis_P ...
- Mybatis分页插件PageHelper的配置和使用方法
Mybatis分页插件PageHelper的配置和使用方法 前言 在web开发过程中涉及到表格时,例如dataTable,就会产生分页的需求,通常我们将分页方式分为两种:前端分页和后端分页. 前端分 ...
- SpringBoot集成MyBatis的分页插件 PageHelper
首先说说MyBatis框架的PageHelper插件吧,它是一个非常好用的分页插件,通常我们的项目中如果集成了MyBatis的话,几乎都会用到它,因为分页的业务逻辑说复杂也不复杂,但是有插件我们何乐而 ...
- (转)淘淘商城系列——MyBatis分页插件(PageHelper)的使用以及商品列表展示
http://blog.csdn.net/yerenyuan_pku/article/details/72774381 上文我们实现了展示后台页面的功能,而本文我们实现的主要功能是展示商品列表,大家要 ...
随机推荐
- 玩转Google开源C++单元测试框架Google Test系列(gtest)(总)
原文地址:http://www.cnblogs.com/coderzh/archive/2009/04/06/1426755.html 前段时间学习和了解了下Google的开源C++单元测试框架Goo ...
- CodeForces - 552E Vanya and Brackets —— 加与乘运算的组合
题目链接:https://vjudge.net/contest/224393#problem/E Vanya is doing his maths homework. He has an expres ...
- Contiki Ctimer模块
Ctimer 提供和Etimer类似的功能,只是Ctimer是在一段时间后调用回调函数,没有和特定进程相关联. 而Etimer是在一段时间后发送PROCESS_EVENT_TIMER事件给特定的进程. ...
- matlab程序计时
t1=datetime(); %程序 t2=datetime() totaltime=t2-t1; disp(t2-t1); 或者: tic %代码块 toc disp(['运行时间: ',num2s ...
- PHP5.3之后的新特性【转】
http://blog.csdn.net/black_ox/article/details/21163193
- web性能压力测试工具http_load/webbench/ad
http_load 下载地址:http://www.acme.com/software/http_load/http_load-12mar2006.tar.gz 程序非常小,解压后也不到100K 居家 ...
- PHP 正则表达示
PHP 正则表达示 php如何使用正则表达式 正则表达式基本元字符 #正则表达式示例 ^:匹配输入字符串开始的位置.如果设置了 RegExp 对象的 Multiline 属性,^ 还会与“\n”或“\ ...
- 「USACO15FEB」「LuoguP3121」审查(黄金)Censoring (Gold)(AC自动机
题目描述 Farmer John has purchased a subscription to Good Hooveskeeping magazine for his cows, so they h ...
- C# 对象间的 深拷贝 实现
以下的这个类实现了 2个含有部分字段名字相同 的对象的 赋值拷贝. public class ShallowCopyHelper { public static voi ...
- RT-Thread信号量使用(动态/静态信号量) 及 信号量的四种使用场合
信号量(Semaphore),有时被称为信号灯,是在多线程环境下使用的一种设施,是可以用来保证两个或多个关键代码段不被并发调用.在进入一个关键代码段之前,线程必须获取一个信号量:一旦该关键代码段完成了 ...