MyBatis具體是什麼東東,這些在後邊在研究吧,本文目的是爲了記錄如何使用MyBatis。java
經過github上能夠找到MyBatis代碼:https://github.com/mybatis/mybatis-3,在最新代碼中能夠下載具體的有代碼包,也能夠下載開發包。mysql
mybatis-config.xmlgit
<?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.propertiesgithub
# #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操做打印到控制檯中。sql
具體其餘方式實現MyBatis操做日誌打印到控制檯,請參考文章:http://blog.csdn.net/qq_17555933/article/details/51656253數據庫
db.propertiesapache
#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
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)
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對象包括:session
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轉化處理類.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()); } }
<?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映射文件中要代表映射類型:oracle
<!-- 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}。
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); }
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(); } }
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 Files\Java\jdk1.8.0_111\bin\java"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