黑马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 上文我们实现了展示后台页面的功能,而本文我们实现的主要功能是展示商品列表,大家要 ...
随机推荐
- 《CSS权威指南(第三版)》---第五章 字体
这章主要的内容有: 1.字体:一般使用一种通用的字体. 2.字体加粗:一般从数字100 -900 . 3.字体大小:font-size 4.拉伸和调整字体:font-stretch 5.调整字体大小: ...
- EntityFramework codefirst
一.Entity Framework 迁移命令(get-help EntityFramework) Enable-Migrations 启用迁移 Add-Migration 为挂起的Model变化添加 ...
- linux系统调用mount全过程分析【转】
本文转载自:https://blog.csdn.net/skyflying2012/article/details/9748133 系统调用本身是软中断,使用系统调用,内核也陷入内核态,异常处理,找到 ...
- javascript正则(带g符号) 多次调用test 结果交替出现
链接:https://segmentfault.com/q/1010000000582051 http://stackoverflow.com/questions/2851308/why-does-m ...
- 去js校验
1.首先,找到项目所在的路径 2.关掉eclipse,找到项目文件 3.打开.project
- linkedin databus介绍——监听数据库变化,有新数据到来时通知其他消费者app,新数据存在内存里,多份快照
概要结构如下图. 图中显示:Search Index和Read Replicas等系统是Databus的消费者.当主OLTP数据库发生写操作时,连接其上的中继系统会将数据拉到中继中.签入在Search ...
- Linux 中安装软件报缺少共享库文件的错误
linux 安装一些如软件 或者相关的模块时,经常报出缺少一些依赖包的 libxxx.so等的共享库文件 首先找到 该共享库文件 然后查看/etc/ld.so.conf 这个文件记录了编译时使用的动态 ...
- 「USACO08DEC」「LuoguP2921」在农场万圣节Trick or Treat on the Farm(tarjan
题意翻译 题目描述 每年,在威斯康星州,奶牛们都会穿上衣服,收集农夫约翰在N(1<=N<=100,000)个牛棚隔间中留下的糖果,以此来庆祝美国秋天的万圣节. 由于牛棚不太大,FJ通过指定 ...
- 网络最大流dinic模板
#include<iostream> #include<cstdio> #include<cstring> #include<queue> using ...
- POJ 3258 最小值最大化 二分搜索
题意:牛要到河对岸,在与河岸垂直的一条线上,河中有N块石头,给定河岸宽度L,以及每一块石头离牛所在河岸的距离, 现在去掉M块石头,要求去掉M块石头后,剩下的石头之间以及石头与河岸的最小距离的最大值. ...