黑马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 上文我们实现了展示后台页面的功能,而本文我们实现的主要功能是展示商品列表,大家要 ...
随机推荐
- iOS数据持久化存储之属性列表
属性列表(plist) iOS提供了一种plist格式的文件(属性列表)用于存储轻量级的数据,属性列表是一种XML格式的文件,拓展名为plist.如果对象是NSString.NSDictionary. ...
- jquery 3D分页翻转滑块
jquery 3D分页翻转滑块,jquery分页,jquery插件,jquery,3D翻转,css3分页,360度旋转,网页特效代码3D分页翻转滑块是一款使用网格样式与滑块效果分页的特效.
- ios审核过程十大常见被拒问题
欢迎加入ios马甲包经验交流群,群聊号码:744520623 2018年伊始,苹果并没有因为新年的气氛而对CP们“网开一面”.频繁锁榜.调整排名规则以及关键词覆盖算法……不断抛出的大动作,让CP们叫苦 ...
- 第三届蓝桥杯预赛c++b组
1.微生物增值 假设有两种微生物 X 和 Y X出生后每隔3分钟分裂一次(数目加倍),Y出生后每隔2分钟分裂一次(数目加倍). 一个新出生的X,半分钟之后吃掉1个Y,并且,从此开始,每 ...
- find命令的基础用法以及按文件修改时间查找文件
一般文件查找方法: find 命令学好是一件很有趣的事情,也可以帮你在查找系统文件的时候事倍功半,还可以与正则表达式结合使用,功能强大,是一个很好的查找工具.可以整体提高你的系统管理能力. 基础用法 ...
- 【LeetCode】Maximum Product Subarray 求连续子数组使其乘积最大
Add Date 2014-09-23 Maximum Product Subarray Find the contiguous subarray within an array (containin ...
- BZOJ-3881:Divljak (AC自动机+DFS序+树链求并+树状数组)
Alice有n个字符串S_1,S_2...S_n,Bob有一个字符串集合T,一开始集合是空的. 接下来会发生q个操作,操作有两种形式: “1 P”,Bob往自己的集合里添加了一个字符串P. “2 x” ...
- BZOJ1146:[CTSC2008]网络管理
浅谈树状数组与线段树:https://www.cnblogs.com/AKMer/p/9946944.html 题目传送门:https://www.lydsy.com/JudgeOnline/prob ...
- MFC ListBox 设置水平长度
在*.rc资源 设置可以水平滚动, 垂直滚动 但是 水平滚动无效,水平方向 一直无法显示 完整 设置代码如下 m_listBox.SetHorizontalExtent(2000); m_listBo ...
- MFC获取数据的方式
假设输入框ID是:ID_NUMBER1,ID_NUMBER2,ID_NUMBER3. 获取数据的方式是: int number1,number2,number3; number1 = GetDlgIt ...