1. 程式人生 > >MyBatis中的JdbcType對映介紹

MyBatis中的JdbcType對映介紹

Java專案涉及到資料庫互動,以往常用的是JDBC,現在則有Hibernate、Mybatis等這些持久化支援。

 

專案中用到了MyBatis,和JDBC最顯著的區別,就是SQL語句配置化,通過xml檔案定義SQL語句,當然JDBC也可以將SQL配置化,需要定製開發,MyBatis則直接支援這種方法。

 

官方對於MyBatis的介紹,

MyBatis is a first class persistence framework with support for custom SQL,   stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.        

 

簡單來講,MyBatis幾乎遮蔽了所有JDBC程式碼,用一種簡單的xml,或者註解,就能完成資料庫互動。

 

xml配置檔案,可用MyBatis自己定義的資料型別,引自:http://www.mybatis.org/mybatis-3/configuration.html

Associated JDBC type can be specified by two means:

  • Adding a jdbcType attribute to the typeHandler element (for example: jdbcType="VARCHAR").

  • Adding a @MappedJdbcTypes annotation to your TypeHandler class specifying the list of JDBC types to associate it with. This annotation will be ignored if the jdbcType attribute as also been specified.

 

例如下面的配置,指定companyid引數型別為BIGINT,

<select id='getMeetingnoByCompanyid' parameterType="java.lang.Integer"
        resultType="java.lang.String">
        select a.meetingno
        from xxx a
        where a.companyid = #{companyid, jdbcType=BIGINT}
</select>

 

對於jdbcType,MyBatis的API文件有說明,引自:http://www.mybatis.org/mybatis-3/apidocs/reference/org/apache/ibatis/type/JdbcType.html

 

另外,這篇文章,給出了JdbcType和Oracle以及MySQL,相互之間的對映關係,比較詳細,引自:http://blog.csdn.net/loongshawn/article/details/50496460

  JdbcType Oracle MySql
JdbcType ARRAY    
JdbcType BIGINT   BIGINT
JdbcType BINARY    
JdbcType BIT   BIT
JdbcType BLOB BLOB BLOB
JdbcType BOOLEAN    
JdbcType CHAR CHAR CHAR
JdbcType CLOB CLOB 修改為TEXT
JdbcType CURSOR    
JdbcType DATE DATE DATE
JdbcType DECIMAL DECIMAL DECIMAL
JdbcType DOUBLE NUMBER DOUBLE
JdbcType FLOAT FLOAT FLOAT
JdbcType INTEGER INTEGER INTEGER
JdbcType LONGVARBINARY    
JdbcType LONGVARCHAR LONG VARCHAR  
JdbcType NCHAR NCHAR  
JdbcType NCLOB NCLOB  
JdbcType NULL    
JdbcType NUMERIC NUMERIC/NUMBER NUMERIC/
JdbcType NVARCHAR    
JdbcType OTHER    
JdbcType REAL REAL REAL
JdbcType SMALLINT SMALLINT SMALLINT
JdbcType STRUCT    
JdbcType TIME   TIME
JdbcType TIMESTAMP TIMESTAMP TIMESTAMP/DATETIME
JdbcType TINYINT   TINYINT
JdbcType UNDEFINED    
JdbcType VARBINARY    
JdbcType VARCHAR VARCHAR VARCHAR