MyBatis使用分页插件

网址

github-中文文档

https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md

github-英文文档

https://github.com/pagehelper/Mybatis-PageHelper

使用方法

https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

api

https://apidoc.gitee.com/free/Mybatis_PageHelper/overview-summary.html

工程

目录结构

工程框架

jar包

entity.User.java

package entity;

public class User {

   
private Integer id;

   
private String username;

   
private String password;

   
private String phone;

   
private String address;

   
public User() {
    }

   
public User(String username, String password, String phone, String address) {
       
this.username = username;
       
this.password = password;
       
this.phone = phone;
       
this.address = address;
    }

   
public User(Integer id, String username, String password, String phone, String address) {
       
this.id = id;
       
this.username = username;
       
this.password = password;
       
this.phone = phone;
       
this.address = address;
    }

   
public Integer getId() {
       
return id;
    }

   
public void setId(Integer id) {
       
this.id = id;
    }

   
public String getUsername() {
       
return username;
    }

   
public void setUsername(String username) {
       
this.username = username == null ? null : username.trim();
    }

   
public String getPassword() {
       
return password;
    }

   
public void setPassword(String password) {
        
this.password = password == null ? null : password.trim();
    }

   
public String getPhone() {
       
return phone;
    }

   
public void setPhone(String phone) {
       
this.phone = phone == null ? null : phone.trim();
    }

   
public String getAddress() {
       
return address;
    }

   
public void setAddress(String address) {
       
this.address = address == null ? null : address.trim();
    }

   
@Override
   
public String toString() {
       
return "User{" +
               
"id=" + id +
               
", username='" + username + '\'' +
               
", password='" + password + '\'' +
               
", phone='" + phone + '\'' +
               
", address='" + address + '\'' +
               
"}\n";
    }
}

entity.UserExample

package entity;

import java.util.ArrayList;
import java.util.List;

public class UserExample {

   
protected String orderByClause;

   
protected boolean distinct;

   
protected List<Criteria> oredCriteria;

   
public UserExample() {
       
oredCriteria = new ArrayList<Criteria>();
    }

   
public void setOrderByClause(String orderByClause) {
       
this.orderByClause = orderByClause;
    }

   
public String getOrderByClause() {
       
return orderByClause;
    }

   
public void setDistinct(boolean distinct) {
       
this.distinct = distinct;
    }

   
public boolean isDistinct() {
       
return distinct;
    }

   
public List<Criteria> getOredCriteria() {
       
return oredCriteria;
    }

   
public void or(Criteria criteria) {
       
oredCriteria.add(criteria);
    }

   
public Criteria or() {
       
Criteria criteria = createCriteriaInternal();
       
oredCriteria.add(criteria);
       
return criteria;
    }

   
public Criteria createCriteria() {
       
Criteria criteria = createCriteriaInternal();
       
if (oredCriteria.size() == 0) {
           
oredCriteria.add(criteria);
        }
       
return criteria;
    }

   
protected Criteria createCriteriaInternal() {
       
Criteria criteria = new Criteria();
       
return criteria;
    }

   
public void clear() {
       
oredCriteria.clear();
       
orderByClause = null;
       
distinct = false;
    }

   
protected abstract static class GeneratedCriteria {
       
protected List<Criterion> criteria;

       
protected GeneratedCriteria() {
           
super();
           
criteria = new ArrayList<Criterion>();
        }

       
public boolean isValid() {
           
return criteria.size() > 0;
        }

       
public List<Criterion> getAllCriteria() {
           
return criteria;
        }

       
public List<Criterion> getCriteria() {
           
return criteria;
        }

       
protected void addCriterion(String condition) {
           
if (condition == null) {
               
throw new RuntimeException("Value for condition cannot be null");
            }
           
criteria.add(new Criterion(condition));
        }

       
protected void addCriterion(String condition, Object value, String property) {
           
if (value == null) {
               
throw new RuntimeException("Value for " + property + " cannot be null");
            }
           
criteria.add(new Criterion(condition, value));
        }

       
protected void addCriterion(String condition, Object value1, Object value2, String property) {
           
if (value1 == null || value2 == null) {
               
throw new RuntimeException("Between values for " + property + " cannot be null");
            }
           
criteria.add(new Criterion(condition, value1, value2));
        }

       
public Criteria andIdIsNull() {
            addCriterion(
"id is null");
           
return (Criteria) this;
        }

       
public Criteria andIdIsNotNull() {
            addCriterion(
"id is not null");
           
return (Criteria) this;
        }

       
public Criteria andIdEqualTo(Integer value) {
            addCriterion(
"id =", value, "id");
           
return (Criteria) this;
        }

       
public Criteria andIdNotEqualTo(Integer value) {
            addCriterion(
"id <>", value, "id");
           
return (Criteria) this;
        }

       
public Criteria andIdGreaterThan(Integer value) {
            addCriterion(
"id >", value, "id");
           
return (Criteria) this;
        }

       
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
            addCriterion(
"id >=", value, "id");
           
return (Criteria) this;
        }

       
public Criteria andIdLessThan(Integer value) {
            addCriterion(
"id <", value, "id");
           
return (Criteria) this;
        }

       
public Criteria andIdLessThanOrEqualTo(Integer value) {
            addCriterion(
"id <=", value, "id");
           
return (Criteria) this;
        }

       
public Criteria andIdIn(List<Integer> values) {
            addCriterion(
"id in", values, "id");
           
return (Criteria) this;
        }

       
public Criteria andIdNotIn(List<Integer> values) {
            addCriterion(
"id not in", values, "id");
           
return (Criteria) this;
        }

       
public Criteria andIdBetween(Integer value1, Integer value2) {
            addCriterion(
"id between", value1, value2, "id");
           
return (Criteria) this;
        }

       
public Criteria andIdNotBetween(Integer value1, Integer value2) {
            addCriterion(
"id not between", value1, value2, "id");
           
return (Criteria) this;
        }

       
public Criteria andUsernameIsNull() {
            addCriterion(
"username is null");
           
return (Criteria) this;
        }

       
public Criteria andUsernameIsNotNull() {
            addCriterion(
"username is not null");
           
return (Criteria) this;
        }

       
public Criteria andUsernameEqualTo(String value) {
            addCriterion(
"username =", value, "username");
           
return (Criteria) this;
        }

       
public Criteria andUsernameNotEqualTo(String value) {
            addCriterion(
"username <>", value, "username");
           
return (Criteria) this;
        }

       
public Criteria andUsernameGreaterThan(String value) {
            addCriterion(
"username >", value, "username");
           
return (Criteria) this;
        }

       
public Criteria andUsernameGreaterThanOrEqualTo(String value) {
            addCriterion(
"username >=", value, "username");
           
return (Criteria) this;
        }

       
public Criteria andUsernameLessThan(String value) {
            addCriterion(
"username <", value, "username");
           
return (Criteria) this;
        }

       
public Criteria andUsernameLessThanOrEqualTo(String value) {
            addCriterion(
"username <=", value, "username");
           
return (Criteria) this;
        }

       
public Criteria andUsernameLike(String value) {
            addCriterion(
"username like", value, "username");
           
return (Criteria) this;
        }

       
public Criteria andUsernameNotLike(String value) {
            addCriterion(
"username not like", value, "username");
           
return (Criteria) this;
        }

       
public Criteria andUsernameIn(List<String> values) {
            addCriterion(
"username in", values, "username");
           
return (Criteria) this;
        }

       
public Criteria andUsernameNotIn(List<String> values) {
            addCriterion(
"username not in", values, "username");
           
return (Criteria) this;
        }

       
public Criteria andUsernameBetween(String value1, String value2) {
            addCriterion(
"username between", value1, value2, "username");
           
return (Criteria) this;
        }

       
public Criteria andUsernameNotBetween(String value1, String value2) {
            addCriterion(
"username not between", value1, value2, "username");
           
return (Criteria) this;
        }

       
public Criteria andPasswordIsNull() {
            addCriterion(
"password is null");
           
return (Criteria) this;
        }

       
public Criteria andPasswordIsNotNull() {
            addCriterion(
"password is not null");
           
return (Criteria) this;
        }

       
public Criteria andPasswordEqualTo(String value) {
            addCriterion(
"password =", value, "password");
           
return (Criteria) this;
        }

       
public Criteria andPasswordNotEqualTo(String value) {
            addCriterion(
"password <>", value, "password");
           
return (Criteria) this;
        }

       
public Criteria andPasswordGreaterThan(String value) {
            addCriterion(
"password >", value, "password");
           
return (Criteria) this;
        }

       
public Criteria andPasswordGreaterThanOrEqualTo(String value) {
            addCriterion(
"password >=", value, "password");
           
return (Criteria) this;
        }

       
public Criteria andPasswordLessThan(String value) {
            addCriterion(
"password <", value, "password");
           
return (Criteria) this;
        }

       
public Criteria andPasswordLessThanOrEqualTo(String value) {
            addCriterion(
"password <=", value, "password");
           
return (Criteria) this;
        }

       
public Criteria andPasswordLike(String value) {
            addCriterion(
"password like", value, "password");
           
return (Criteria) this;
        }

       
public Criteria andPasswordNotLike(String value) {
            addCriterion(
"password not like", value, "password");
           
return (Criteria) this;
        }

       
public Criteria andPasswordIn(List<String> values) {
            addCriterion(
"password in", values, "password");
           
return (Criteria) this;
        }

       
public Criteria andPasswordNotIn(List<String> values) {
            addCriterion(
"password not in", values, "password");
           
return (Criteria) this;
        }

       
public Criteria andPasswordBetween(String value1, String value2) {
            addCriterion(
"password between", value1, value2, "password");
           
return (Criteria) this;
        }

       
public Criteria andPasswordNotBetween(String value1, String value2) {
            addCriterion(
"password not between", value1, value2, "password");
           
return (Criteria) this;
        }

       
public Criteria andPhoneIsNull() {
            addCriterion(
"phone is null");
           
return (Criteria) this;
        }

       
public Criteria andPhoneIsNotNull() {
            addCriterion(
"phone is not null");
           
return (Criteria) this;
        }

       
public Criteria andPhoneEqualTo(String value) {
            addCriterion(
"phone =", value, "phone");
           
return (Criteria) this;
        }

       
public Criteria andPhoneNotEqualTo(String value) {
            addCriterion(
"phone <>", value, "phone");
           
return (Criteria) this;
        }

       
public Criteria andPhoneGreaterThan(String value) {
            addCriterion(
"phone >", value, "phone");
           
return (Criteria) this;
        }

       
public Criteria andPhoneGreaterThanOrEqualTo(String value) {
            addCriterion(
"phone >=", value, "phone");
           
return (Criteria) this;
        }

       
public Criteria andPhoneLessThan(String value) {
            addCriterion(
"phone <", value, "phone");
           
return (Criteria) this;
        }

       
public Criteria andPhoneLessThanOrEqualTo(String value) {
            addCriterion(
"phone <=", value, "phone");
           
return (Criteria) this;
        }

       
public Criteria andPhoneLike(String value) {
            addCriterion(
"phone like", value, "phone");
           
return (Criteria) this;
        }

       
public Criteria andPhoneNotLike(String value) {
            addCriterion(
"phone not like", value, "phone");
           
return (Criteria) this;
        }

       
public Criteria andPhoneIn(List<String> values) {
            addCriterion(
"phone in", values, "phone");
           
return (Criteria) this;
        }

       
public Criteria andPhoneNotIn(List<String> values) {
            addCriterion(
"phone not in", values, "phone");
            
return (Criteria) this;
        }

       
public Criteria andPhoneBetween(String value1, String value2) {
            addCriterion(
"phone between", value1, value2, "phone");
           
return (Criteria) this;
        }

       
public Criteria andPhoneNotBetween(String value1, String value2) {
            addCriterion(
"phone not between", value1, value2, "phone");
           
return (Criteria) this;
        }

       
public Criteria andAddressIsNull() {
            addCriterion(
"address is null");
           
return (Criteria) this;
        }

       
public Criteria andAddressIsNotNull() {
            addCriterion(
"address is not null");
           
return (Criteria) this;
        }

       
public Criteria andAddressEqualTo(String value) {
            addCriterion(
"address =", value, "address");
           
return (Criteria) this;
        }

       
public Criteria andAddressNotEqualTo(String value) {
            addCriterion(
"address <>", value, "address");
           
return (Criteria) this;
        }

       
public Criteria andAddressGreaterThan(String value) {
            addCriterion(
"address >", value, "address");
           
return (Criteria) this;
        }

       
public Criteria andAddressGreaterThanOrEqualTo(String value) {
            addCriterion(
"address >=", value, "address");
           
return (Criteria) this;
        }

       
public Criteria andAddressLessThan(String value) {
            addCriterion(
"address <", value, "address");
           
return (Criteria) this;
        }

       
public Criteria andAddressLessThanOrEqualTo(String value) {
            addCriterion(
"address <=", value, "address");
           
return (Criteria) this;
        }

       
public Criteria andAddressLike(String value) {
            addCriterion(
"address like", value, "address");
           
return (Criteria) this;
        }

       
public Criteria andAddressNotLike(String value) {
            addCriterion(
"address not like", value, "address");
           
return (Criteria) this;
        }

        
public Criteria andAddressIn(List<String> values) {
            addCriterion(
"address in", values, "address");
           
return (Criteria) this;
        }

       
public Criteria andAddressNotIn(List<String> values) {
            addCriterion(
"address not in", values, "address");
           
return (Criteria) this;
        }

       
public Criteria andAddressBetween(String value1, String value2) {
            addCriterion(
"address between", value1, value2, "address");
           
return (Criteria) this;
        }

       
public Criteria andAddressNotBetween(String value1, String value2) {
            addCriterion(
"address not between", value1, value2, "address");
           
return (Criteria) this;
        }
    }

   
public static class Criteria extends GeneratedCriteria {

       
protected Criteria() {
           
super();
        }
    }

   
public static class Criterion {
       
private String condition;

       
private Object value;

       
private Object secondValue;

       
private boolean noValue;

       
private boolean singleValue;

       
private boolean betweenValue;

       
private boolean listValue;

       
private String typeHandler;

       
public String getCondition() {
           
return condition;
        }

       
public Object getValue() {
           
return value;
        }

       
public Object getSecondValue() {
           
return secondValue;
        }

       
public boolean isNoValue() {
           
return noValue;
        }

       
public boolean isSingleValue() {
           
return singleValue;
        }

       
public boolean isBetweenValue() {
           
return betweenValue;
        }

       
public boolean isListValue() {
           
return listValue;
        }

       
public String getTypeHandler() {
            
return typeHandler;
        }

       
protected Criterion(String condition) {
           
super();
           
this.condition = condition;
           
this.typeHandler = null;
           
this.noValue = true;
        }

       
protected Criterion(String condition, Object value, String typeHandler) {
           
super();
           
this.condition = condition;
           
this.value = value;
           
this.typeHandler = typeHandler;
           
if (value instanceof List<?>) {
               
this.listValue = true;
            }
else {
               
this.singleValue = true;
            }
        }

       
protected Criterion(String condition, Object value) {
           
this(condition, value, null);
        }

       
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
           
super();
           
this.condition = condition;
           
this.value = value;
           
this.secondValue = secondValue;
           
this.typeHandler = typeHandler;
            
this.betweenValue = true;
        }

       
protected Criterion(String condition, Object value, Object secondValue) {
           
this(condition, value, secondValue, null);
        }
    }
}

dao.UserMapper.java

package dao;

import entity.User;
import entity.UserExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {

   
int countByExample(UserExample example);

   
int deleteByExample(UserExample example);

   
int deleteByPrimaryKey(Integer id);

   
int insert(User record);

   
int insertSelective(User record);

   
List<User> selectByExample(UserExample example);

   
User selectByPrimaryKey(Integer id);

   
int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);

   
int updateByExample(@Param("record") User record, @Param("example") UserExample example);

   
int updateByPrimaryKeySelective(User record);

   
int updateByPrimaryKey(User record);
}

mapper.Usermapper.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="dao.UserMapper" >
  <
resultMap id="BaseResultMap" type="entity.User" >
   
    <
id column="id" property="id" jdbcType="INTEGER" />
    <
result column="username" property="username" jdbcType="VARCHAR" />
    <
result column="password" property="password" jdbcType="VARCHAR" />
    <
result column="phone" property="phone" jdbcType="VARCHAR" />
    <
result column="address" property="address" jdbcType="VARCHAR" />
  </
resultMap>
  <
sql id="Example_Where_Clause" >
   
    <
where >
      <
foreach collection="oredCriteria" item="criteria" separator="or" >
        <
if test="criteria.valid" >
          <
trim prefix="(" suffix=")" prefixOverrides="and" >
            <
foreach collection="criteria.criteria" item="criterion" >
              <
choose >
                <
when test="criterion.noValue" >
                  and ${criterion.condition}
                </
when>
                <
when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </
when>
                <
when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </
when>
                <
when test="criterion.listValue" >
                  and ${criterion.condition}
                  <
foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </
foreach>
                </
when>
              </
choose>
            </
foreach>
          </
trim>
        </
if>
      </
foreach>
    </
where>
  </
sql>
  <
sql id="Update_By_Example_Where_Clause" >
   
    <
where >
      <
foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <
if test="criteria.valid" >
          <
trim prefix="(" suffix=")" prefixOverrides="and" >
            <
foreach collection="criteria.criteria" item="criterion" >
              <
choose >
                <
when test="criterion.noValue" >
                  and ${criterion.condition}
                </
when>
                <
when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </
when>
                <
when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </
when>
                <
when test="criterion.listValue" >
                  and ${criterion.condition}
                  <
foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </
foreach>
                </
when>
              </
choose>
            </
foreach>
          </
trim>
        </
if>
      </
foreach>
    </
where>
  </
sql>
  <
sql id="Base_Column_List" >
   
    id, username, password, phone, address
  </
sql>
  <
select id="selectByExample" resultMap="BaseResultMap" parameterType="entity.UserExample" >
   
    select
    <
if test="distinct" >
      distinct
    </
if>
    <
include refid="Base_Column_List" />
    from t_user
    <
if test="_parameter != null" >
      <
include refid="Example_Where_Clause" />
    </
if>
    <
if test="orderByClause != null" >
      order by ${orderByClause}
    </
if>
  </
select>
  <
select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
   
    select
    <
include refid="Base_Column_List" />
    from t_user
    where id = #{id,jdbcType=INTEGER}
  </
select>
  <
delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
   
    delete from t_user
    where id = #{id,jdbcType=INTEGER}
  </
delete>
  <
delete id="deleteByExample" parameterType="entity.UserExample" >
   
    delete from t_user
    <
if test="_parameter != null" >
      <
include refid="Example_Where_Clause" />
    </
if>
  </
delete>
  <
insert id="insert" parameterType="entity.User" useGeneratedKeys="true" keyProperty="id">
   
    insert into t_user (id, username, password,
      phone, address)
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
      #{phone,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR})
  </
insert>
  <
insert id="insertSelective" parameterType="entity.User"  useGeneratedKeys="true" keyProperty="id">
   
    insert into t_user
    <
trim prefix="(" suffix=")" suffixOverrides="," >
      <
if test="id != null" >
        id,
      </
if>
      <
if test="username != null" >
        username,
      </
if>
      <
if test="password != null" >
        password,
      </
if>
      <
if test="phone != null" >
        phone,
      </
if>
      <
if test="address != null" >
        address,
      </
if>
    </
trim>
    <
trim prefix="values (" suffix=")" suffixOverrides="," >
      <
if test="id != null" >
        #{id,jdbcType=INTEGER},
      </
if>
      <
if test="username != null" >
        #{username,jdbcType=VARCHAR},
      </
if>
      <
if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </
if>
      <
if test="phone != null" >
        #{phone,jdbcType=VARCHAR},
      </
if>
      <
if test="address != null" >
        #{address,jdbcType=VARCHAR},
      </
if>
    </
trim>
  </
insert>
  <
select id="countByExample" parameterType="entity.UserExample" resultType="java.lang.Integer" >
   
    select
count(*) from t_user
    <
if test="_parameter != null" >
      <
include refid="Example_Where_Clause" />
    </
if>
  </
select>
  <
update id="updateByExampleSelective" parameterType="map" >
   
    update t_user
    <
set >
      <
if test="record.id != null" >
        id = #{record.id,jdbcType=INTEGER},
      </
if>
      <
if test="record.username != null" >
        username = #{record.username,jdbcType=VARCHAR},
      </
if>
      <
if test="record.password != null" >
        password = #{record.password,jdbcType=VARCHAR},
      </
if>
      <
if test="record.phone != null" >
        phone = #{record.phone,jdbcType=VARCHAR},
      </
if>
      <
if test="record.address != null" >
        address = #{record.address,jdbcType=VARCHAR},
      </
if>
    </
set>
    <
if test="_parameter != null" >
      <
include refid="Update_By_Example_Where_Clause" />
    </
if>
  </
update>
  <
update id="updateByExample" parameterType="map" >
   
    update t_user
    set id = #{record.id,jdbcType=INTEGER},
      username = #{record.username,jdbcType=VARCHAR},
      password = #{record.password,jdbcType=VARCHAR},
      phone = #{record.phone,jdbcType=VARCHAR},
      address = #{record.address,jdbcType=VARCHAR}
    <
if test="_parameter != null" >
      <
include refid="Update_By_Example_Where_Clause" />
    </
if>
  </
update>
  <
update id="updateByPrimaryKeySelective" parameterType="entity.User" >
   
    update t_user
    <
set >
      <
if test="username != null" >
        username = #{username,jdbcType=VARCHAR},
      </
if>
      <
if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </
if>
      <
if test="phone != null" >
        phone = #{phone,jdbcType=VARCHAR},
      </
if>
      <
if test="address != null" >
        address = #{address,jdbcType=VARCHAR},
      </
if>
    </
set>
    where id = #{id,jdbcType=INTEGER}
  </
update>
  <
update id="updateByPrimaryKey" parameterType="entity.User" >
   
    update t_user
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      phone = #{phone,jdbcType=VARCHAR},
      address = #{address,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </
update>
</
mapper>

dataSource.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&serverTimezone=UTC&charaterEncoding=utf-8
jdbc.username=root
jdbc.password=graspaa

log4j.properties

log4j.rootLogger=debug,console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-5p %m%n

log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.PreparedStatement=DEBUG

mybatis-config.xml

<?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="dataSource.properties"/>

    <
typeAliases>
        <
package name="entity"/>
    </
typeAliases>

    <
plugins>
       
<!-- 配置分页插件 -->
        <!-- com.github.pagehelper
PageHelper类所在包名,如果没有导入jar包,就会报MyBatisUtil.java的错 -->
       
<plugin interceptor="com.github.pagehelper.PageHelper">
        </
plugin>
    </
plugins>
   
    <
environments default="hello">
        <
environment id="hello">
            <
transactionManager type="jdbc"></transactionManager>
            <
dataSource type="POOLED">
                <
property name="driver" value="${jdbc.driver}"/>
                <
property name="url" value="${jdbc.url}"/>
                <
property name="username" value="${jdbc.username}"/>
                <
property name="password" value="${jdbc.password}"/>
            </
dataSource>
        </
environment>
    </
environments>

    <
mappers>
        <
mapper resource="mapper/UserMapper.xml"/>
    </
mappers>
</
configuration>

util.MyBatisUtil.java

package util;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * Author: xian
 * Date: 2020-06-19 13:40
 * description:
 */

public class MyBatisUtil {
   
public static SqlSessionFactory sqlSessionFactory;
   
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();

   
static {
       
try {
           
sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(
MyBatisUtil.class.getClassLoader().getResourceAsStream("mybatis-config.xml"));
        }
catch (Exception e) {
           
throw new ExceptionInInitializerError("MyBatisUtil初始化失败:" + e.getMessage());
        }
    }

   
public static SqlSession getSession() {
       
SqlSession sqlSession = threadLocal.get();
       
if (sqlSession == null) {
            sqlSession =
sqlSessionFactory.openSession();
           
threadLocal.set(sqlSession);
        }
       
return sqlSession;
    }

   
public static void close() {
       
SqlSession sqlSession = threadLocal.get();
       
if (sqlSession != null) {
           
sqlSession.close();
           
threadLocal.remove();
        }
    }
}

test.Test

package test;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import dao.UserMapper;
import entity.User;
import entity.UserExample;
import org.apache.ibatis.session.SqlSession;
import util.MyBatisUtil;

import java.util.List;

/**
 * Author: xian
 * Date: 2020-06-22 10:20
 * description:
 */

public class Test {
   
public static void main(String[] args) {
       
SqlSession session = null;
       
try {
            session =
MyBatisUtil.getSession();

           
UserMapper userMapper = session.getMapper(UserMapper.class);

           
//String temp = "j";
            //User user = new User(8, temp, temp, null, temp);
            //User user1 = userMapper.selectByPrimaryKey(7);

            //UserExample userExample = new UserExample();
            //userExample.or().andUsernameEqualTo("e")
            //                .andPasswordEqualTo("e");
            //
            //userExample.or().andAddressEqualTo("c");
            //List<User> users = userMapper.selectByExample(userExample);
            //System.out.println(users);

           
int pageNum = 2;
           
int pageSize = 4;
           
PageHelper.startPage(pageNum, pageSize);

           
List<User> users = userMapper.selectByExample(new UserExample());
           
PageInfo<User> userPageInfo = new PageInfo<>(users);
           
System.out.println(userPageInfo);
           
System.out.println("\n");

           
int pageNum1 = userPageInfo.getPageNum();
           
int pageSize1 = userPageInfo.getPageSize();
           
int pages = userPageInfo.getPages();
           
long total = userPageInfo.getTotal();
           
System.out.println("第几页:"+pageNum1);
           
System.out.println("页大小:"+pageSize1);
           
System.out.println("总页数:"+pages);
           
System.out.println("数据总共有几条:"+total);

           
System.out.println("\n");
           
for (User user : users) {
               
System.out.println(user);
            }
           
//System.out.println(users);

           
session.commit();
        }
catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }
finally {
           
MyBatisUtil.close();
        }
    }
}

运行

源码

https://gitee.com/xian1990/mybatis/tree/noob

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值