zoukankan      html  css  js  c++  java
  • MyBatis(一):配置并使用

    MyBatis具体是什么东东,这些在后边在研究吧,本文目的是为了记录如何使用MyBatis。

    • 首先,需要下载MyBatis开发所需要文件。

    通过github上可以找到MyBatis代码:https://github.com/mybatis/mybatis-3,在最新代码中可以下载具体的有代码包,也可以下载开发包。

    • 解压MyBatis后把其中的Jar包引入工程中:

    • 在工程下边添加配置文件:

    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>
        <!-- 引用db.properties配置文件 -->
        <properties resource="resources/db.properties"/>
        <typeAliases>
            <package name="com.xxx.entity"/>
        </typeAliases>
        <!-- 对事务的管理和连接池的配置 -->
        <environments default="mysql_jdbc">
            <environment id="oracle_jdbc">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${name}"/>
                    <property name="password" value="${password}"/>
                </dataSource>
            </environment>
    
            <environment id="mysql_jdbc">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${name}"/>
                    <property name="password" value="${password}"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper resource="resources/mapper/TaskAutoExecutePlanMapper.xml"/>
        </mappers>
    </configuration>

    log4j.properties

    # #define DEBUG priority, R
    # log4j.rootLogger = INFO, R
    # # configure log output type as file
    # log4j.appender.R = org.apache.log4j.DailyRollingFileAppender
    # #log filename
    # log4j.appender.R.file = ./logRecord.log
    # # append
    # log4j.appender.R.Append = true
    # log4j.appender.R.layout = org.apache.log4j.PatternLayout
    # log4j.appender.R.layout.ConversionPattern = %n%d%p[%l]%m%n
    #
    # log4j.appender.R.DatePattern='.' yyyy-MM-dd
    
    
    log4j.rootLogger=DEBUG, Console
    #Console
    log4j.appender.Console=org.apache.log4j.ConsoleAppender
    log4j.appender.Console.layout=org.apache.log4j.PatternLayout
    log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
    log4j.logger.java.sql.ResultSet=INFO
    log4j.logger.org.apache=INFO
    log4j.logger.java.sql.Connection=DEBUG
    log4j.logger.java.sql.Statement=DEBUG
    log4j.logger.java.sql.PreparedStatement=DEBUG

    这里主要目的是实现把MyBatis的sql操作打印到控制台中。

    具体其他方式实现MyBatis操作日志打印到控制台,请参考文章:http://blog.csdn.net/qq_17555933/article/details/51656253

    db.properties

    #oracle.jdbc.driver.OracleDriver | com.mysql.jdbc.Driver
    driver=com.mysql.jdbc.Driver
    #jdbc:oracle:thin:@localhost:1521:orcl | jdbc:mysql://localhost:3306/mybatis
    url=jdbc:mysql://localhost:3306/mybatis
    name=root
    password=123456
    • 新建mysql库:MyBatis,新建表TaskAutoExecutePlan

    create databases mybatis;
    
    create table TaskAutoExecutePlan(
    id varchar(64) CHARACTER SET utf8mb4 NOT NULL DEFAULT '0',
    autoExecutePlanType varchar(36)  NOT NULL default '0',
    taskStatus varchar(36)  NOT NULL default '0',
    createDate datetime not null DEFAULT CURRENT_TIMESTAMP,
    modifyDate datetime not null DEFAULT CURRENT_TIMESTAMP)
    • 新建实体类TaskAutoExecutePlan.java

    package com.xxx.entity;
    
    import java.util.UUID;
    import java.util.Date;
    
    /**
     * Created by Administrator on 2017/2/19.
     */
    public class TaskAutoExecutePlan {
        /**
         * create databases mybatis;
         *
         * create table TaskAutoExecutePlan(
         * `id` varchar(36) CHARACTER SET utf8mb4 NOT NULL DEFAULT '0',
         * 'autoExecutePlanType' integer default '0',
         * 'taskStatus' integer default '0',
         * 'createDate' datetime DEFAULT CURRENT_TIMESTAMP,
         * 'modifyDate' datetime DEFAULT CURRENT_TIMESTAMP)
         * */
        private String id=null;
        private AutoExecutePlanType autoExecutePlanType;
        private TaskStatus taskStatus;
        private Date createDate;
        private Date modifyDate;
    
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public AutoExecutePlanType getAutoExecutePlanType() {
            return autoExecutePlanType;
        }
    
        public void setAutoExecutePlanType(AutoExecutePlanType autoExecutePlanType) {
            this.autoExecutePlanType = autoExecutePlanType;
        }
    
        public TaskStatus getTaskStatus() {
            return taskStatus;
        }
    
        public void setTaskStatus(TaskStatus taskStatus) {
            this.taskStatus = taskStatus;
        }
    
        public Date getCreateDate() {
            return createDate;
        }
    
        public void setCreateDate(Date createDate) {
            this.createDate = createDate;
        }
    
        public Date getModifyDate() {
            return modifyDate;
        }
    
        public void setModifyDate(Date modifyDate) {
            this.modifyDate = modifyDate;
        }
    }

    设计到的enum对象包括:

    AutoExecutePlanType.java
    TaskStatus.java
    package com.xxxx.entity;
    
    /**
     * Created by Administrator on 2017/2/19.<br>
     * 任务状态:<br>
     * 2:Todo,待处理状态<br>
     * 4:Doing,正在处理状态<br>
     * 8:Success,已成功处理<br>
     * 16:Fail;已失败<br>
     * */
    public enum TaskStatus {
        /**
         * 2:Todo,待处理状态
        * */
        Todo(2),
        /**
         * 4:Doing,正在处理状态
         * */
        Doing(4),
        /**
         * 8:Success,已成功处理
         * */
        Success(8),
        /**
         * 16:Fail;已失败
         * */
        Fail(16);
    
        private Integer value;
        private TaskStatus(int value){
            setValue(value);
        }
    
        public static TaskStatus valueOf(int value){
            switch(value){
                case 2:
                    return Todo;
                case 4:
                    return Doing;
                case 8:
                    return Success;
                case 16:
                    return Fail;
                default:
                    return null;
            }
        }
    
        public Integer getValue() {
            return value;
        }
        private void setValue(int value) {
            this.value = value;
        }
    }

    为了实现mybatis映射enum类型需要添加一个每个enum对象的一个mybatis转化处理类.

    package com.xxx.entity;
    
    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;
    
    /**
     * Created by Administrator on 2017/2/20.
     */
    public class TaskStatusHandler extends BaseTypeHandler<TaskStatus> {
        private Class<TaskStatus> type;
        private final TaskStatus[] enums;
    
        /**
         * 设置配置文件设置的转换类以及枚举类内容,供其他方法更便捷高效的实现
         *
         * @param type 配置文件中设置的转换类
         */
        public TaskStatusHandler(Class<TaskStatus> type) {
            if (type == null)
                throw new IllegalArgumentException("Type argument cannot be null");
            this.type = type;
            this.enums = type.getEnumConstants();
            if (this.enums == null)
                throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
        }
    
    
        @Override
        public void setNonNullParameter(PreparedStatement preparedStatement, int i, TaskStatus autoExecutePlanType, JdbcType jdbcType) throws SQLException {
            // baseTypeHandler已经帮我们做了parameter的null判断
            preparedStatement.setInt(i, autoExecutePlanType.getValue());
        }
    
        @Override
        public TaskStatus getNullableResult(ResultSet resultSet, String s) throws SQLException {
            // 根据数据库存储类型决定获取类型,本例子中数据库中存放INT类型
            int i = resultSet.getInt(s);
    
            if (resultSet.wasNull()) {
                return null;
            } else { // 根据数据库中的code值,定位EnumStatus子类
                return locateEnumStatus(i);
            }
        }
    
        @Override
        public TaskStatus getNullableResult(ResultSet resultSet, int i) throws SQLException {
            // 根据数据库存储类型决定获取类型,本例子中数据库中存放INT类型
            int index = resultSet.getInt(i);
            if (resultSet.wasNull()) {
                return null;
            } else { // 根据数据库中的code值,定位EnumStatus子类
                return locateEnumStatus(index);
            }
        }
    
        @Override
        public TaskStatus getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
            // 根据数据库存储类型决定获取类型,本例子中数据库中存放INT类型
            int index = callableStatement.getInt(i);
            if (callableStatement.wasNull()) {
                return null;
            } else {
                // 根据数据库中的code值,定位EnumStatus子类
                return locateEnumStatus(index);
            }
        }
    
        /**
         * 枚举类型转换,由于构造函数获取了枚举的子类enums,让遍历更加高效快捷
         *
         * @param code 数据库中存储的自定义code属性
         * @return code对应的枚举类
         */
        private TaskStatus locateEnumStatus(int code) {
            for (TaskStatus status : enums) {
                if (status.getValue().equals(Integer.valueOf(code))) {
                    return status;
                }
            }
            throw new IllegalArgumentException("未知的枚举类型:" + code + ",请核对" + type.getSimpleName());
        }
    }
    • 配置TaskAutoExecutePlan映射文件:

    <?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.xxx.mapper.TaskAutoExecutePlanMapper">
        <!--
        private UUID id=null;
        private AutoExecutePlanType autoExecutePlanType;
        private TaskStatus taskStatus;
        private Date createDate;
        private Date modifyDate;
        -->
        <resultMap type="TaskAutoExecutePlan" id="TaskAutoExecutePlanResult">
            <result column="id" property="id"/>
            <result column="autoExecutePlanType" property="autoExecutePlanType" typeHandler="com.xxx.entity.AutoExecutePlanTypeHandler"/>
            <result column="taskStatus" property="taskStatus" typeHandler="com.xxx.entity.TaskStatusHandler"/>
            <result column="createDate" property="createDate" jdbcType="TIMESTAMP" javaType="java.sql.Timestamp"/>
            <result column="modifyDate" property="modifyDate" jdbcType="TIMESTAMP" javaType="java.sql.Timestamp"/>
        </resultMap>
        <select id="getAll" resultType="TaskAutoExecutePlan" resultMap="TaskAutoExecutePlanResult">
            select * from TaskAutoExecutePlan
        </select>
        <insert id="insert" parameterType="TaskAutoExecutePlan">
            <selectKey keyProperty="id" resultType="String" order="BEFORE">
                select  replace(uuid(),'-','')   from dual
            </selectKey>
            insert into TaskAutoExecutePlan (id,autoExecutePlanType,taskStatus,createDate,modifyDate)
            values (#{id,jdbcType=VARCHAR},
            #{autoExecutePlanType,jdbcType=BIT,typeHandler=com.xxx.entity.AutoExecutePlanTypeHandler},
            #{taskStatus,jdbcType=BIT,typeHandler=com.xxx.entity.TaskStatusHandler},
            #{createDate,jdbcType=TIMESTAMP},
            #{modifyDate,jdbcType=TIMESTAMP})
        </insert>
    </mapper>

    当涉及到日期操作时,需要注视事项:
    在MyBatis映射文件中要表明映射类型:

    <!-- jdbcType="TIMESTAMP"入库后保存精确日期为:yyyy-MM-dd HH:mm:ss-->
    <result column="CreateDate" jdbcType="TIMESTAMP" property="createDate" javaType="java.sql.Timestamp" /> 
    <!-- jdbcType="DATE"入库后保存精确日期为:yyyy-MM-dd -->
    <result column="ModifyDate" jdbcType="DATE" property="modifyDate" javaType="java.util.Date" />

    在使用字段的时候也要标明类型#{createDate,jdbcType=TIMESTAMP}、#{modifyDate,jdbcType=DATE}。

    • 编写数据操作接口类TaskAutoExecutePlanMapper.java:

    package com.xxx.mapper;
    
    import com.xxx.entity.TaskAutoExecutePlan;
    
    import java.util.List;
    
    /**
     * Created by Administrator on 2017/2/17.
     */
    public interface TaskAutoExecutePlanMapper {
        public List<TaskAutoExecutePlan> getAll();
        public void insert(TaskAutoExecutePlan taskAutoExecutePlan);
    
    }
    • 编写业务类TaskAutoExecutePlanServer.java:

    package com.xxx.service;
    
    import java.io.InputStream;
    import java.util.List;
    
    import com.xxx.entity.TaskAutoExecutePlan;
    import com.xxx.mapper.TaskAutoExecutePlanMapper;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    /**
     * Created by Administrator on 2017/2/20.
     */
    public class TaskAutoExecutePlanServer implements TaskAutoExecutePlanMapper {
        private final String resource = "resources/mybatis-config.xml";
        private SqlSessionFactory factory = null;
    
        public TaskAutoExecutePlanServer() {
            InputStream is = TaskAutoExecutePlanServer.class.getClassLoader().getResourceAsStream(resource);
            factory = new SqlSessionFactoryBuilder().build(is);
        }
    
        @Override
        public List<TaskAutoExecutePlan> getAll() {
            SqlSession sqlSession = this.factory.openSession();
            List<TaskAutoExecutePlan> result = sqlSession.selectList("com.xxx.mapper.TaskAutoExecutePlanMapper.getAll");
            sqlSession.commit();
            sqlSession.close();
    
            return result;
        }
    
        @Override
        public void insert(TaskAutoExecutePlan taskAutoExecutePlan) {
            SqlSession sqlSession = this.factory.openSession();
            sqlSession.insert("com.xxx.mapper.TaskAutoExecutePlanMapper.insert",taskAutoExecutePlan);
            sqlSession.commit();
            sqlSession.close();
        }
    
    
    }
    • 测试类Main.java

    public static void main(String[] args) {
            TaskAutoExecutePlanServer taskAutoExecutePlanServer = new TaskAutoExecutePlanServer();
            TaskAutoExecutePlan taskAutoExecutePlan = new TaskAutoExecutePlan();
            taskAutoExecutePlan.setId("BC");
            taskAutoExecutePlan.setAutoExecutePlanType(AutoExecutePlanType.MxRasterization);
            taskAutoExecutePlan.setTaskStatus(TaskStatus.Doing);
            taskAutoExecutePlan.setCreateDate(new Date());
            taskAutoExecutePlan.setModifyDate(new Date());
            taskAutoExecutePlanServer.insert(taskAutoExecutePlan);
    
            List<TaskAutoExecutePlan> items = taskAutoExecutePlanServer.getAll();
            for (TaskAutoExecutePlan item : items)
                System.out.println(item.getId() + "," + item.getAutoExecutePlanType() + "," + item.getTaskStatus() + "," + item.getCreateDate() + "," + item.getModifyDate());
    
            Log log = LogUtil.getInstance(MainThread.class);
    }

    输出结果:

    "D:Program FilesJavajdk1.8.0_111injava"2017-02-21 01:06:54,465 [main] DEBUG [com.xxx.mapper.TaskAutoExecutePlanMapper.insert!selectKey] - ==>  Preparing: select replace(uuid(),'-','') from dual 
    2017-02-21 01:06:54,509 [main] DEBUG [com.xxx.mapper.TaskAutoExecutePlanMapper.insert!selectKey] - ==> Parameters: 
    2017-02-21 01:06:54,548 [main] DEBUG [com.xxx.mapper.TaskAutoExecutePlanMapper.insert!selectKey] - <==      Total: 1
    2017-02-21 01:06:54,549 [main] DEBUG [com.xxx.mapper.TaskAutoExecutePlanMapper.insert] - ==>  Preparing: insert into TaskAutoExecutePlan (id,autoExecutePlanType,taskStatus,createDate,modifyDate) values (?, ?, ?, ?, ?) 
    2017-02-21 01:06:54,563 [main] DEBUG [com.xxx.mapper.TaskAutoExecutePlanMapper.insert] - ==> Parameters: fa07695af78e11e69fb300fffdc16f2e(String), 256(Integer), 4(Integer), 2017-02-21 01:06:54.124(Timestamp), 2017-02-21 01:06:54.124(Timestamp)
    2017-02-21 01:06:54,565 [main] DEBUG [com.xxx.mapper.TaskAutoExecutePlanMapper.insert] - <==    Updates: 1
    2017-02-21 01:06:54,574 [main] DEBUG [com.xxx.mapper.TaskAutoExecutePlanMapper.getAll] - ==>  Preparing: select * from TaskAutoExecutePlan 
    2017-02-21 01:06:54,575 [main] DEBUG [com.xxx.mapper.TaskAutoExecutePlanMapper.getAll] - ==> Parameters: 
    2017-02-21 01:06:54,587 [main] DEBUG [com.xxx.mapper.TaskAutoExecutePlanMapper.getAll] - <==      Total: 7
    b82e7600f78d11e69fb300fffdc16f2e,MxRasterization,Doing,2017-02-21 00:57:54.0,2017-02-21 00:00:00.0
    cc754dacf78d11e69fb300fffdc16f2e,MxRasterization,Doing,2017-02-21 00:58:28.0,2017-02-21 00:58:28.0
    2e6cb0a8f78e11e69fb300fffdc16f2e,MxRasterization,Doing,2017-02-21 01:01:12.0,2017-02-21 01:01:12.0
    3cfe4f81f78e11e69fb300fffdc16f2e,MxRasterization,Doing,2017-02-21 01:01:36.0,2017-02-21 01:01:36.0
    576b7b93f78e11e69fb300fffdc16f2e,MxRasterization,Doing,2017-02-21 01:02:21.0,2017-02-21 01:02:21.0
    a5de9916f78e11e69fb300fffdc16f2e,MxRasterization,Doing,2017-02-21 01:04:32.0,2017-02-21 01:04:32.0
    fa07695af78e11e69fb300fffdc16f2e,MxRasterization,Doing,2017-02-21 01:06:54.0,2017-02-21 01:06:54.0
  • 相关阅读:
    关于我的新博客
    我今天申请了blog!
    Win XP / Win 7上配置eclipse+CDT+MinGW,和相关问题的解决办法
    Android app Installation error: INSTALL_FAILED_CONFLICTING_PROVIDER
    用adb安装程序,和在电脑和设备之间传文件
    eclipse 断点调试快捷键(转)
    找不到设备,device not found错误
    eclipse里面的C printf 先输出到缓冲区
    Eclipse Outline 图示
    如何获得Android系统版本
  • 原文地址:https://www.cnblogs.com/yy3b2007com/p/6422276.html
Copyright © 2011-2022 走看看