Java MyBatis3实例


MyBatisClien.java 入口类。读取配置文件,生成SqlSessionFactory,使用DAO操作表。

package cn.aofeng.demo.mybatis;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.aofeng.demo.mybatis.dao.MonitNotifyHistoryDao;
import cn.aofeng.demo.mybatis.entity.MonitNotifyHistory;

public class MyBatisClient {

    private static Logger _logger = LoggerFactory.getLogger(MyBatisClient.class);

    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream ins = Resources.getResourceAsStream(resource);
        SqlSessionFactory ssFactory = new SqlSessionFactoryBuilder().build(ins);
        MonitNotifyHistoryDao dao = new MonitNotifyHistoryDao(ssFactory);

        // 插入一条记录
        long recordId = 999;
        MonitNotifyHistory record = new MonitNotifyHistory();
        record.setRecordId(recordId);
        record.setMonitId(9999);
        record.setAppId(99);
        record.setNotifyTarget(1);
        record.setNotifyType(1);
        record.setNotifyContent("通知内容测试");
        record.setStatus(0);
        record.setCreateTime(1492061400000L);
        int count = dao.insert(record);
        _logger.info("insert complete, effects {} rows", count);

        // 查询记录
        MonitNotifyHistory entity = dao.selectByPrimaryKey(recordId);
        _logger.info("query record id {}, result: {}", recordId, entity);

        // 更新一个字段再执行查询
        entity.setRetryTimes(99);
        count = dao.updateByPrimaryKeySelective(entity);
        _logger.info("update complete, record id:{}, effects {} rows", recordId, count);
        entity = dao.selectByPrimaryKey(recordId);
        _logger.info("query record id {}, result: {}", recordId, entity);

        // 删除记录后再执行查询
        count = dao.deleteByPrimaryKey(recordId);
        _logger.info("delete complete, record id {}, effects {} rows", recordId, count);
        entity = dao.selectByPrimaryKey(recordId);
        _logger.info("query record id {}, result: {}", recordId, entity);
    }
}

mybatis-config.xml mybatis配置文件

<?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>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://192.168.56.102:19816/ucgc_monit?useUnicode=true&amp;characterEncoding=UTF8"/>
        <property name="username" value="uzone"/>
        <property name="password" value="uzone"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="cn/aofeng/demo/mybatis/mapper/MonitNotifyHistoryMapper.xml"/>
  </mappers>
</configuration>

MonitNotifyHistoryDao DAO类

package cn.aofeng.demo.mybatis.dao;

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

import cn.aofeng.demo.mybatis.entity.MonitNotifyHistory;

/**
 * 监控通知历史CURD。
 */
public class MonitNotifyHistoryDao {

    private SqlSessionFactory _ssFactory = null;

    public MonitNotifyHistoryDao(SqlSessionFactory factory) {
        this._ssFactory = factory;
    }

    private String assembleStatement(String id) {
        return "cn.aofeng.demo.mybatis.dao.MonitNotifyHistoryMapper."+id;
    }

    private void close(SqlSession session) {
        if (null != session) {
            session.close();
        }
    }

    public int deleteByPrimaryKey(Long recordId) {
        SqlSession session = _ssFactory.openSession(true);
        int result = 0;
        try {
            session.delete(assembleStatement("deleteByPrimaryKey"), recordId);
        } finally {
            close(session);
        }

        return result;
    }

    public int insert(MonitNotifyHistory record) {
        SqlSession session = _ssFactory.openSession(true);
        int result = 0;
        try {
            result = session.insert(assembleStatement("insertSelective"), record);
        } finally {
            close(session);
        }

        return result;
    }

    public MonitNotifyHistory selectByPrimaryKey(Long recordId) {
        SqlSession session = _ssFactory.openSession();
        MonitNotifyHistory result = null;
        try {
            result = session.selectOne(assembleStatement("selectByPrimaryKey"), recordId);
        } finally {
            close(session);
        }

        return result;
    }

    public int updateByPrimaryKeySelective(MonitNotifyHistory record) {
        SqlSession session = _ssFactory.openSession(true);
        int result = 0;
        try {
            session.update(assembleStatement("updateByPrimaryKeySelective"), record);
        } finally {
            close(session);
        }

        return result;
    }

}

MonitNotifyHisto.java 实体类

package cn.aofeng.demo.mybatis.entity;

/**
 * 监控通知历史实体类。
 *
 */
public class MonitNotifyHistory {
    private Long recordId;

    private Integer monitId;

    private Integer appId;

    private Integer notifyType;

    private Integer notifyTarget;

    private String notifyContent;

    private Integer status;

    private Integer retryTimes;

    private Long createTime;

    public Long getRecordId() {
        return recordId;
    }

    public void setRecordId(Long recordId) {
        this.recordId = recordId;
    }

    public Integer getMonitId() {
        return monitId;
    }

    public void setMonitId(Integer monitId) {
        this.monitId = monitId;
    }

    public Integer getAppId() {
        return appId;
    }

    public void setAppId(Integer appId) {
        this.appId = appId;
    }

    public Integer getNotifyType() {
        return notifyType;
    }

    public void setNotifyType(Integer notifyType) {
        this.notifyType = notifyType;
    }

    public Integer getNotifyTarget() {
        return notifyTarget;
    }

    public void setNotifyTarget(Integer notifyTarget) {
        this.notifyTarget = notifyTarget;
    }

    public String getNotifyContent() {
        return notifyContent;
    }

    public void setNotifyContent(String notifyContent) {
        this.notifyContent = notifyContent;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Integer getRetryTimes() {
        return retryTimes;
    }

    public void setRetryTimes(Integer retryTimes) {
        this.retryTimes = retryTimes;
    }

    public Long getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Long createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "MonitNotifyHistory [recordId=" + recordId + ", monitId=" + monitId + ", appId=" + appId + ", notifyType=" + notifyType + ", notifyTarget="
                + notifyTarget + ", notifyContent=" + notifyContent + ", status=" + status + ", retryTimes=" + retryTimes + ", createTime=" + createTime + "]";
    }
}

MonitNotifyHistoryMapper.xml SQL模板映射配置文件

<?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="cn.aofeng.demo.mybatis.dao.MonitNotifyHistoryMapper">
  <resultMap id="BaseResultMap" type="cn.aofeng.demo.mybatis.entity.MonitNotifyHistory">
    <id column="record_id" jdbcType="BIGINT" property="recordId" />
    <result column="monit_id" jdbcType="INTEGER" property="monitId" />
    <result column="app_id" jdbcType="TINYINT" property="appId" />
    <result column="notify_type" jdbcType="TINYINT" property="notifyType" />
    <result column="notify_target" jdbcType="INTEGER" property="notifyTarget" />
    <result column="notify_content" jdbcType="VARCHAR" property="notifyContent" />
    <result column="status" jdbcType="TINYINT" property="status" />
    <result column="retry_times" jdbcType="TINYINT" property="retryTimes" />
    <result column="create_time" jdbcType="BIGINT" property="createTime" />
  </resultMap>

  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    select record_id, monit_id, app_id, notify_type, notify_target, notify_content, status,
      retry_times, create_time
    from monit_notify_history
    where record_id = #{recordId,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    delete from monit_notify_history
    where record_id = #{recordId,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="cn.aofeng.demo.mybatis.entity.MonitNotifyHistory">
    insert into monit_notify_history (record_id, monit_id, app_id,
      notify_type, notify_target, notify_content,
      status, retry_times, create_time
      )
    values (#{recordId,jdbcType=BIGINT}, #{monitId,jdbcType=INTEGER}, #{appId,jdbcType=TINYINT},
      #{notifyType,jdbcType=TINYINT}, #{notifyTarget,jdbcType=INTEGER}, #{notifyContent,jdbcType=VARCHAR},
      #{status,jdbcType=TINYINT}, #{retryTimes,jdbcType=TINYINT}, #{createTime,jdbcType=BIGINT}
      )
  </insert>
  <insert id="insertSelective" parameterType="cn.aofeng.demo.mybatis.entity.MonitNotifyHistory">
    insert into monit_notify_history
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="recordId != null">
        record_id,
      </if>
      <if test="monitId != null">
        monit_id,
      </if>
      <if test="appId != null">
        app_id,
      </if>
      <if test="notifyType != null">
        notify_type,
      </if>
      <if test="notifyTarget != null">
        notify_target,
      </if>
      <if test="notifyContent != null">
        notify_content,
      </if>
      <if test="status != null">
        status,
      </if>
      <if test="retryTimes != null">
        retry_times,
      </if>
      <if test="createTime != null">
        create_time,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="recordId != null">
        #{recordId,jdbcType=BIGINT},
      </if>
      <if test="monitId != null">
        #{monitId,jdbcType=INTEGER},
      </if>
      <if test="appId != null">
        #{appId,jdbcType=TINYINT},
      </if>
      <if test="notifyType != null">
        #{notifyType,jdbcType=TINYINT},
      </if>
      <if test="notifyTarget != null">
        #{notifyTarget,jdbcType=INTEGER},
      </if>
      <if test="notifyContent != null">
        #{notifyContent,jdbcType=VARCHAR},
      </if>
      <if test="status != null">
        #{status,jdbcType=TINYINT},
      </if>
      <if test="retryTimes != null">
        #{retryTimes,jdbcType=TINYINT},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=BIGINT},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="cn.aofeng.demo.mybatis.entity.MonitNotifyHistory">
    update monit_notify_history
    <set>
      <if test="monitId != null">
        monit_id = #{monitId,jdbcType=INTEGER},
      </if>
      <if test="appId != null">
        app_id = #{appId,jdbcType=TINYINT},
      </if>
      <if test="notifyType != null">
        notify_type = #{notifyType,jdbcType=TINYINT},
      </if>
      <if test="notifyTarget != null">
        notify_target = #{notifyTarget,jdbcType=INTEGER},
      </if>
      <if test="notifyContent != null">
        notify_content = #{notifyContent,jdbcType=VARCHAR},
      </if>
      <if test="status != null">
        status = #{status,jdbcType=TINYINT},
      </if>
      <if test="retryTimes != null">
        retry_times = #{retryTimes,jdbcType=TINYINT},
      </if>
      <if test="createTime != null">
        create_time = #{createTime,jdbcType=BIGINT},
      </if>
    </set>
    where record_id = #{recordId,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="cn.aofeng.demo.mybatis.entity.MonitNotifyHistory">
    update monit_notify_history
    set monit_id = #{monitId,jdbcType=INTEGER},
      app_id = #{appId,jdbcType=TINYINT},
      notify_type = #{notifyType,jdbcType=TINYINT},
      notify_target = #{notifyTarget,jdbcType=INTEGER},
      notify_content = #{notifyContent,jdbcType=VARCHAR},
      status = #{status,jdbcType=TINYINT},
      retry_times = #{retryTimes,jdbcType=TINYINT},
      create_time = #{createTime,jdbcType=BIGINT}
    where record_id = #{recordId,jdbcType=BIGINT}
  </update>
</mapper>

更多Java MyBatis教程

学习更多Java MyBatis教程