Mybatis(学习三)--增删改查
程序员文章站
2022-07-14 08:50:16
...
1.创建maven项目
2.配置pom.xml文件
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lq</groupId>
<artifactId>Mybatis01</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Mybatis01 Maven Webapp</name>
<url>http://maven.apache.org</url>
<!-- 设置UTF-8编码格式 -->
<properties>
<!-- 文件拷贝时的编码 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 编译时的编码 -->
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<!-- 自定义常量,在依赖中可以通过${名字}的方式进行引用 -->
<spring.version>4.3.14.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--显示日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<!-- 单元测试配置 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- jdk版本配置 -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.数据库配置:database.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///mysql
username=root
password=root
4.mybatis配置文件: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="database.properties"/>
<!-- 环境配置 -->
<environments default="lq">
<environment id="lq">
<!-- 事务管理器的配置 -->
<transactionManager type="JDBC"/>
<!-- 基本信息配置 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 注册映射元文件 -->
<mappers>
<mapper resource="com/lq/mapper/UserBeanMapper.xml"/>
</mappers>
</configuration>
5.日志输出配置:log4j.properties
log4j.rootLogger=ALL, Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%m%n
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=INFO
6.反向工程文件配置:generator.xml
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="context1" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true" />
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql:///mysql" userId="root" password="root">
</jdbcConnection>
<javaModelGenerator targetPackage="com.lq.entity"
targetProject="Mybatis01">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.lq.mapper"
targetProject="Mybatis01">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.lq.dao" implementationPackage="com.lq.dao.impl"
targetProject="Mybatis01">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<table tableName="t_users" domainObjectName="UserBean">
</table>
</context>
</generatorConfiguration>
7.反向生成的实体类:
package com.lq.entity;
import java.math.BigDecimal;
import java.util.Date;
public class UserBean {
private Long id;
private String username;
private String password;
private Date birth;
private Boolean sex;
private BigDecimal salary;
public Long getId() {
return id;
}
public void setId(Long 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 getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Boolean getSex() {
return sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
@Override
public String toString() {
return "UserBean [id=" + id + ", username=" + username + ", password=" + password + ", birth=" + birth
+ ", sex=" + sex + ", salary=" + salary + "]";
}
}
package com.lq.entity;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class UserBeanExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public UserBeanExample() {
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(Long value) {
addCriterion("Id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Long value) {
addCriterion("Id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Long value) {
addCriterion("Id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Long value) {
addCriterion("Id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Long value) {
addCriterion("Id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Long value) {
addCriterion("Id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Long> values) {
addCriterion("Id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Long> values) {
addCriterion("Id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Long value1, Long value2) {
addCriterion("Id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Long value1, Long 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 andBirthIsNull() {
addCriterion("Birth is null");
return (Criteria) this;
}
public Criteria andBirthIsNotNull() {
addCriterion("Birth is not null");
return (Criteria) this;
}
public Criteria andBirthEqualTo(Date value) {
addCriterion("Birth =", value, "birth");
return (Criteria) this;
}
public Criteria andBirthNotEqualTo(Date value) {
addCriterion("Birth <>", value, "birth");
return (Criteria) this;
}
public Criteria andBirthGreaterThan(Date value) {
addCriterion("Birth >", value, "birth");
return (Criteria) this;
}
public Criteria andBirthGreaterThanOrEqualTo(Date value) {
addCriterion("Birth >=", value, "birth");
return (Criteria) this;
}
public Criteria andBirthLessThan(Date value) {
addCriterion("Birth <", value, "birth");
return (Criteria) this;
}
public Criteria andBirthLessThanOrEqualTo(Date value) {
addCriterion("Birth <=", value, "birth");
return (Criteria) this;
}
public Criteria andBirthIn(List<Date> values) {
addCriterion("Birth in", values, "birth");
return (Criteria) this;
}
public Criteria andBirthNotIn(List<Date> values) {
addCriterion("Birth not in", values, "birth");
return (Criteria) this;
}
public Criteria andBirthBetween(Date value1, Date value2) {
addCriterion("Birth between", value1, value2, "birth");
return (Criteria) this;
}
public Criteria andBirthNotBetween(Date value1, Date value2) {
addCriterion("Birth not between", value1, value2, "birth");
return (Criteria) this;
}
public Criteria andSexIsNull() {
addCriterion("Sex is null");
return (Criteria) this;
}
public Criteria andSexIsNotNull() {
addCriterion("Sex is not null");
return (Criteria) this;
}
public Criteria andSexEqualTo(Boolean value) {
addCriterion("Sex =", value, "sex");
return (Criteria) this;
}
public Criteria andSexNotEqualTo(Boolean value) {
addCriterion("Sex <>", value, "sex");
return (Criteria) this;
}
public Criteria andSexGreaterThan(Boolean value) {
addCriterion("Sex >", value, "sex");
return (Criteria) this;
}
public Criteria andSexGreaterThanOrEqualTo(Boolean value) {
addCriterion("Sex >=", value, "sex");
return (Criteria) this;
}
public Criteria andSexLessThan(Boolean value) {
addCriterion("Sex <", value, "sex");
return (Criteria) this;
}
public Criteria andSexLessThanOrEqualTo(Boolean value) {
addCriterion("Sex <=", value, "sex");
return (Criteria) this;
}
public Criteria andSexIn(List<Boolean> values) {
addCriterion("Sex in", values, "sex");
return (Criteria) this;
}
public Criteria andSexNotIn(List<Boolean> values) {
addCriterion("Sex not in", values, "sex");
return (Criteria) this;
}
public Criteria andSexBetween(Boolean value1, Boolean value2) {
addCriterion("Sex between", value1, value2, "sex");
return (Criteria) this;
}
public Criteria andSexNotBetween(Boolean value1, Boolean value2) {
addCriterion("Sex not between", value1, value2, "sex");
return (Criteria) this;
}
public Criteria andSalaryIsNull() {
addCriterion("Salary is null");
return (Criteria) this;
}
public Criteria andSalaryIsNotNull() {
addCriterion("Salary is not null");
return (Criteria) this;
}
public Criteria andSalaryEqualTo(BigDecimal value) {
addCriterion("Salary =", value, "salary");
return (Criteria) this;
}
public Criteria andSalaryNotEqualTo(BigDecimal value) {
addCriterion("Salary <>", value, "salary");
return (Criteria) this;
}
public Criteria andSalaryGreaterThan(BigDecimal value) {
addCriterion("Salary >", value, "salary");
return (Criteria) this;
}
public Criteria andSalaryGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("Salary >=", value, "salary");
return (Criteria) this;
}
public Criteria andSalaryLessThan(BigDecimal value) {
addCriterion("Salary <", value, "salary");
return (Criteria) this;
}
public Criteria andSalaryLessThanOrEqualTo(BigDecimal value) {
addCriterion("Salary <=", value, "salary");
return (Criteria) this;
}
public Criteria andSalaryIn(List<BigDecimal> values) {
addCriterion("Salary in", values, "salary");
return (Criteria) this;
}
public Criteria andSalaryNotIn(List<BigDecimal> values) {
addCriterion("Salary not in", values, "salary");
return (Criteria) this;
}
public Criteria andSalaryBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("Salary between", value1, value2, "salary");
return (Criteria) this;
}
public Criteria andSalaryNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("Salary not between", value1, value2, "salary");
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);
}
}
}
8.反向生成的接口
package com.lq.dao;
import com.lq.entity.UserBean;
import com.lq.entity.UserBeanExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UserBeanMapper {
int countByExample(UserBeanExample example);
int deleteByExample(UserBeanExample example);
int deleteByPrimaryKey(Long id);
int insert(UserBean record);
int insertSelective(UserBean record);
List<UserBean> selectByExample(UserBeanExample example);
UserBean selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") UserBean record, @Param("example") UserBeanExample example);
int updateByExample(@Param("record") UserBean record, @Param("example") UserBeanExample example);
int updateByPrimaryKeySelective(UserBean record);
int updateByPrimaryKey(UserBean record);
}
9.反向生成的映射文件:UserBeanMapper.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.lq.dao.UserBeanMapper" >
<resultMap id="BaseResultMap" type="com.lq.entity.UserBean" >
<id column="Id" property="id" jdbcType="BIGINT" />
<result column="Username" property="username" jdbcType="VARCHAR" />
<result column="Password" property="password" jdbcType="VARCHAR" />
<result column="Birth" property="birth" jdbcType="TIMESTAMP" />
<result column="Sex" property="sex" jdbcType="BIT" />
<result column="Salary" property="salary" jdbcType="DECIMAL" />
</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, Birth, Sex, Salary
</sql>
<select id="selectByExample" resultMap="BaseResultMap" parameterType="com.lq.entity.UserBeanExample" >
select
<if test="distinct" >
distinct
</if>
<include refid="Base_Column_List" />
from t_users
<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.Long" >
select
<include refid="Base_Column_List" />
from t_users
where Id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
delete from t_users
where Id = #{id,jdbcType=BIGINT}
</delete>
<delete id="deleteByExample" parameterType="com.lq.entity.UserBeanExample" >
delete from t_users
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.lq.entity.UserBean" >
insert into t_users (Id, Username, Password,
Birth, Sex, Salary)
values (#{id,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{birth,jdbcType=TIMESTAMP}, #{sex,jdbcType=BIT}, #{salary,jdbcType=DECIMAL})
</insert>
<insert id="insertSelective" parameterType="com.lq.entity.UserBean" >
insert into t_users
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
Id,
</if>
<if test="username != null" >
Username,
</if>
<if test="password != null" >
Password,
</if>
<if test="birth != null" >
Birth,
</if>
<if test="sex != null" >
Sex,
</if>
<if test="salary != null" >
Salary,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=BIGINT},
</if>
<if test="username != null" >
#{username,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
<if test="birth != null" >
#{birth,jdbcType=TIMESTAMP},
</if>
<if test="sex != null" >
#{sex,jdbcType=BIT},
</if>
<if test="salary != null" >
#{salary,jdbcType=DECIMAL},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.lq.entity.UserBeanExample" resultType="java.lang.Integer" >
select count(*) from t_users
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map" >
update t_users
<set >
<if test="record.id != null" >
Id = #{record.id,jdbcType=BIGINT},
</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.birth != null" >
Birth = #{record.birth,jdbcType=TIMESTAMP},
</if>
<if test="record.sex != null" >
Sex = #{record.sex,jdbcType=BIT},
</if>
<if test="record.salary != null" >
Salary = #{record.salary,jdbcType=DECIMAL},
</if>
</set>
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map" >
update t_users
set Id = #{record.id,jdbcType=BIGINT},
Username = #{record.username,jdbcType=VARCHAR},
Password = #{record.password,jdbcType=VARCHAR},
Birth = #{record.birth,jdbcType=TIMESTAMP},
Sex = #{record.sex,jdbcType=BIT},
Salary = #{record.salary,jdbcType=DECIMAL}
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.lq.entity.UserBean" >
update t_users
<set >
<if test="username != null" >
Username = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null" >
Password = #{password,jdbcType=VARCHAR},
</if>
<if test="birth != null" >
Birth = #{birth,jdbcType=TIMESTAMP},
</if>
<if test="sex != null" >
Sex = #{sex,jdbcType=BIT},
</if>
<if test="salary != null" >
Salary = #{salary,jdbcType=DECIMAL},
</if>
</set>
where Id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.lq.entity.UserBean" >
update t_users
set Username = #{username,jdbcType=VARCHAR},
Password = #{password,jdbcType=VARCHAR},
Birth = #{birth,jdbcType=TIMESTAMP},
Sex = #{sex,jdbcType=BIT},
Salary = #{salary,jdbcType=DECIMAL}
where Id = #{id,jdbcType=BIGINT}
</update>
</mapper>
10.工具类:MybatisSessionFactory
package com.lq.util;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisSessionFactory {
private MybatisSessionFactory(){
}
private static SqlSessionFactory factory;
private final static ThreadLocal<SqlSession>ts = new ThreadLocal<>();
static{
try {
//解析xml文件并创建SqlSessionFactory对象
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static <T>T getMapper(Class<T>clazz){
SqlSession session=getSession();
if(session != null)
return session.getMapper(clazz);
return null;
}
//提交事务
public static void commitTransaction(){
SqlSession ss =ts.get();
if(ss!= null)
ss.commit();
}
//事务回滚
public static void rollbackTransaction(){
SqlSession ss = ts.get();
if(ss!= null)
ss.rollback();
}
public static SqlSession getSession() {
SqlSession ss =ts.get();
if(ss == null){
ss=factory != null ? factory.openSession():null;
ts.set(ss);
}
return ss;
}
public static void closeSession(){
SqlSession ss = ts.get();
ts.set(null);
if(ss!=null)
ss.close();
}
public static SqlSessionFactory getFactory(){
return factory;
}
}
11.测试类
package com.lq.test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class ConnTest {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sf.openSession();
Connection conn = session.getConnection();
System.out.println(conn);
}
}
package com.lq.test;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.lq.dao.UserBeanMapper;
import com.lq.entity.UserBean;
import com.lq.entity.UserBeanExample;
import com.lq.entity.UserBeanExample.Criteria;
import com.lq.util.MybatisSessionFactory;
public class Test1 {
private UserBeanMapper userMapper;
@Before
public void setUp() throws Exception {
MybatisSessionFactory.getSession();
userMapper = MybatisSessionFactory.getMapper(UserBeanMapper.class);
}
@After
public void tearDown() throws Exception {
MybatisSessionFactory.commitTransaction();
MybatisSessionFactory.closeSession();
}
@Test
//增
public void testSave() {
UserBean user = new UserBean();
user.setUsername("张三");
user.setPassword("123456");
user.setSalary(new BigDecimal(12345.34));
int i = userMapper.insert(user);
assertEquals(1, i);
}
@Test
//删
public void testDel(){
int i = userMapper.deleteByPrimaryKey(5L);
assertEquals(1, i);
}
@Test
//改
public void testModify(){
//先按照指定id加载对象
UserBean userBean = userMapper.selectByPrimaryKey(7L);
System.out.println(userBean);
//修改非id属性
userBean.setSex(false);
userBean.setUsername("王五");
//执行修改动作
int i = userMapper.updateByPrimaryKey(userBean);
assertEquals(1,i);
}
@Test
//查
public void testGetByExample(){
UserBeanExample example = new UserBeanExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameLike("张%");
criteria.andPasswordEqualTo("123456");
criteria.andIdIsNotNull();
List<UserBean> list = userMapper.selectByExample(example);
for (UserBean userBean : list) {
System.out.println(userBean);
}
}
@Test
public void testCountByExample(){
UserBeanExample example = new UserBeanExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameLike("张%");
criteria.andPasswordEqualTo("123456");
criteria.andIdIsNotNull();
int count = userMapper.countByExample(example);
System.out.println("满足条件的行数为:"+count);
}
}