黑马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 上文我们实现了展示后台页面的功能,而本文我们实现的主要功能是展示商品列表,大家要 ...
随机推荐
- SpringBoot2.0之整合ActiveMQ(发布订阅模式)
发布订阅模式与前面的点对点模式很类似,简直一毛一样 注意:发布订阅模式 先启动消费者 公用pom: <project xmlns="http://maven.apache.org/PO ...
- ES搜索排序,文档相关度评分介绍——TF-IDF—term frequency, inverse document frequency, and field-length norm—are calculated and stored at index time.
Theory Behind Relevance Scoring Lucene (and thus Elasticsearch) uses the Boolean model to find match ...
- L90
On Motes and Beams 微尘与栋梁 It is curious that our own offenses should seem so much less heinous than t ...
- stack_1.设计一个有getMin功能的栈
思路 : 生成两个栈($stack ,$stack_min ),往$stack塞数据($value)的时候 ,比较一下$value和$stack_min最上面的元素的大小,如果$value小,则压入$ ...
- MCI支持的格式在注册表中的位置
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion
- hdfs 查看报告--命令(hdfs dfsadmin -report)
[hadoop@master sbin]$ hdfs dfsadmin -reportConfigured Capacity: 8202977280 (7.64 GB)Present Capacity ...
- P1912 [NOI2009]诗人小G[决策单调性优化]
地址 n个数划分若干段,给定$L$,$p$,每段代价为$|sum_i-sum_j-1-L|^p$,求总代价最小. 正常的dp决策单调性优化题目.不知道为什么luogu给了个黑题难度.$f[i]$表示最 ...
- JavaScript:bootstrap 模态框的简单应用
最近用上了bootstrap这个强大的前端框架,有空来总结一下.这里记录下模态框的简单应用. 首先,要在页面中引入相应的js.css文件 <link href="css/bootstr ...
- UE4 框架
转自:http://www.cnblogs.com/NEOCSL/p/4059841.html 有很多人是从UE3 接触到Unreal,如果你也对UE3非常了解,便能很快的上手UE4.但是,UE4的开 ...
- [poj3140]Contestants Division树形dp
题意:切掉树上的某条边,使分开的两棵树上各点的权值和差值最小. 与hdu2196不同的是,此题是点权,其他无太大差别,注意数据范围. 先求出每个节点的子树权值和,然后自底向上dp即可.取$\min ( ...