標籤:
今天學習http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html。關於mapper.xml的sql語句的使用。
項目路徑:https://github.com/chenxing12/l4mybatis
首先,準備環境。
1.建立project
在parent項目上右鍵,new model->maven->mybatis-mapper.
填充pom.xml
<?xml version="1.0" encoding="UTF-8"?><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/xsd/maven-4.0.0.xsd"> <parent> <artifactId>l4mybatis</artifactId> <groupId>com.test</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>mytatis-mapper</artifactId> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build></project>
在resources下添加log4j.properties:
log4j.rootLogger=DEBUG, stdout, logfilelog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%nlog4j.appender.logfile=org.apache.log4j.RollingFileAppenderlog4j.appender.logfile.File=log/test.loglog4j.appender.logfile.MaxFileSize=128MBlog4j.appender.logfile.MaxBackupIndex=3log4j.appender.logfile.layout=org.apache.log4j.PatternLayoutlog4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c.%M(%L) - %m%n
在resources下添加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="db.properties"/> <typeAliases> <package name="com.test.mapper.model"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com.test.mapper.mapper/PersonMapper.xml"/> </mappers></configuration>
在resources下添加db.properties:
#jdbc.driver=com.mysql.jdbc.Driverjdbc.driver=com.mysql.cj.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&useSSL=falsejdbc.username=rootjdbc.password=123456
在資料庫mybatis中建立一個person表:
/*Navicat MySQL Data TransferSource Server : localhostSource Server Version : 50605Source Host : localhost:3306Source Database : mybatisTarget Server Type : MYSQLTarget Server Version : 50605File Encoding : 65001Date: 2016-07-06 22:22:34*/SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for person-- ----------------------------DROP TABLE IF EXISTS `person`;CREATE TABLE `person` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;-- ------------------------------ Records of person-- ----------------------------INSERT INTO `person` VALUES (‘1‘, ‘Ryan‘);
在resources下建立com.test.mapper.mapper/PersonMapper.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.test.mapper.dao.PersonMapper"> <select id="selectPerson" parameterType="int" resultType="hashmap"> select * from person where id = #{id} </select></mapper>
在java下建立com.test.mapper.dao.PersonMapper.java:
package com.test.mapper.dao;import java.util.HashMap;/** * Created by miaorf on 2016/7/6. */public interface PersonMapper { HashMap selectPerson(int id);}
在java下添加:com.test.mapper.model.Person:
package com.test.mapper.model;import java.io.Serializable;/** * Created by miaorf on 2016/7/6. */public class Person implements Serializable { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person{" + "id=" + id + ", name=‘" + name + ‘\‘‘ + ‘}‘; }}
測試環境:
在test下建立com.test.mapper.dao.PersonMapperTest:
package com.test.mapper.dao;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Before;import org.junit.BeforeClass;import org.junit.Test;import java.io.IOException;import java.util.HashMap;import static org.junit.Assert.*;/** * Created by miaorf on 2016/7/6. */public class PersonMapperTest { private SqlSession sqlSession; private static SqlSessionFactory sqlSessionFactory; @BeforeClass public static void init() throws IOException { String config = "mybatis-config.xml"; sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(config)); } @Before public void setUp() throws Exception { sqlSession = sqlSessionFactory.openSession(); } @Test public void selectPerson() throws Exception { PersonMapper mapper = sqlSession.getMapper(PersonMapper.class); HashMap map = mapper.selectPerson(1); System.out.println(map); }}
運行:
2016-07-06 22:23:31,962 DEBUG [org.apache.ibatis.logging.LogFactory] - Logging initialized using ‘class org.apache.ibatis.logging.slf4j.Slf4jImpl‘ adapter.2016-07-06 22:23:32,128 DEBUG [org.apache.ibatis.io.VFS] - Class not found: org.jboss.vfs.VFS2016-07-06 22:23:32,129 DEBUG [org.apache.ibatis.io.JBoss6VFS] - JBoss 6 VFS API is not available in this environment.2016-07-06 22:23:32,131 DEBUG [org.apache.ibatis.io.VFS] - Class not found: org.jboss.vfs.VirtualFile2016-07-06 22:23:32,132 DEBUG [org.apache.ibatis.io.VFS] - VFS implementation org.apache.ibatis.io.JBoss6VFS is not valid in this environment.2016-07-06 22:23:32,134 DEBUG [org.apache.ibatis.io.VFS] - Using VFS adapter org.apache.ibatis.io.DefaultVFS2016-07-06 22:23:32,135 DEBUG [org.apache.ibatis.io.DefaultVFS] - Find JAR URL: file:/D:/workspace/mybatis/l4mybatis/mytatis-mapper/target/classes/com/test/mapper/model2016-07-06 22:23:32,135 DEBUG [org.apache.ibatis.io.DefaultVFS] - Not a JAR: file:/D:/workspace/mybatis/l4mybatis/mytatis-mapper/target/classes/com/test/mapper/model2016-07-06 22:23:32,213 DEBUG [org.apache.ibatis.io.DefaultVFS] - Reader entry: Person.class2016-07-06 22:23:32,214 DEBUG [org.apache.ibatis.io.DefaultVFS] - Listing file:/D:/workspace/mybatis/l4mybatis/mytatis-mapper/target/classes/com/test/mapper/model2016-07-06 22:23:32,214 DEBUG [org.apache.ibatis.io.DefaultVFS] - Find JAR URL: file:/D:/workspace/mybatis/l4mybatis/mytatis-mapper/target/classes/com/test/mapper/model/Person.class2016-07-06 22:23:32,215 DEBUG [org.apache.ibatis.io.DefaultVFS] - Not a JAR: file:/D:/workspace/mybatis/l4mybatis/mytatis-mapper/target/classes/com/test/mapper/model/Person.class2016-07-06 22:23:32,217 DEBUG [org.apache.ibatis.io.DefaultVFS] - Reader entry: ???? 1 62016-07-06 22:23:32,220 DEBUG [org.apache.ibatis.io.ResolverUtil] - Checking to see if class com.test.mapper.model.Person matches criteria [is assignable to Object]2016-07-06 22:23:32,306 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - PooledDataSource forcefully closed/removed all connections.2016-07-06 22:23:32,307 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - PooledDataSource forcefully closed/removed all connections.2016-07-06 22:23:32,309 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - PooledDataSource forcefully closed/removed all connections.2016-07-06 22:23:32,310 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - PooledDataSource forcefully closed/removed all connections.2016-07-06 22:23:32,511 DEBUG [org.apache.ibatis.transaction.jdbc.JdbcTransaction] - Opening JDBC Connection2016-07-06 22:23:32,842 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - Created connection 733672688.2016-07-06 22:23:32,842 DEBUG [org.apache.ibatis.transaction.jdbc.JdbcTransaction] - Setting autocommit to false on JDBC Connection [[email protected]]2016-07-06 22:23:32,847 DEBUG [com.test.mapper.dao.PersonMapper.selectPerson] - ==> Preparing: select * from person where id = ? 2016-07-06 22:23:32,911 DEBUG [com.test.mapper.dao.PersonMapper.selectPerson] - ==> Parameters: 1(Integer)2016-07-06 22:23:32,946 DEBUG [com.test.mapper.dao.PersonMapper.selectPerson] - <== Total: 1{name=Ryan, id=1}
2.select
查詢語句。負責拼接查詢語句並將查詢結果映射出來。上例中:
<select id="selectPerson" parameterType="int" resultType="hashmap"> SELECT * FROM PERSON WHERE ID = #{id}</select>
- 這個語句的id為selectPerson,這個就是對應mapper介面中的方法的名字。
- parameterType是輸入參數類型為int。
- resultType表示查詢結果映射為HashMap
- #{id}是預留位置,相當於JDBC中採用PreparedStatement時sql語句中的問號,表示參數名為id的參數值會替換這個位置。
注意到mapper.xml的namespace就是指向所對應的mapper 介面:
<mapper namespace="com.test.mapper.dao.PersonMapper">
在mapper介面中的方法要和mapper.xml中的id所一一對應。因此,這個查詢的節點對應的mapper介面的方法為:
public interface PersonMapper { HashMap selectPerson(int id);}
事實上,select節點的選擇性參數有以下幾種:
<select id="selectPerson" parameterType="int" parameterMap="deprecated" resultType="hashmap" resultMap="personResultMap" flushCache="false" useCache="true" timeout="10000" fetchSize="256" statementType="PREPARED" resultSetType="FORWARD_ONLY">
文檔對各個參數含義給出瞭解釋:
Select Attributes
| 屬性 |
描述 |
| id |
在命名空間中唯一的標識符,可以被用來引用這條語句。 |
| parameterType |
將會傳入這條語句的參數類的完全限定名或別名。這個屬性是可選的,因為 MyBatis 可以通過 TypeHandler 推斷出具體傳入語句的參數,預設值為 unset。 |
| parameterMap |
這是引用外部 parameterMap 的已經被廢棄的方法。使用內聯參數映射和 parameterType 屬性。 |
| resultType |
從這條語句中返回的期望類型的類的完全限定名或別名。注意如果是集合情形,那應該是集合可以包含的類型,而不能是集合本身。使用 resultType 或 resultMap,但不能同時使用。 |
| resultMap |
外部 resultMap 的命名引用。結果集的映射是 MyBatis 最強大的特性,對其有一個很好的理解的話,許多複雜映射的情形都能迎刃而解。使用 resultMap 或 resultType,但不能同時使用。 |
| flushCache |
將其設定為 true,任何時候只要語句被調用,都會導致本機快取和二級緩衝都會被清空,預設值:false。 |
| useCache |
將其設定為 true,將會導致本條語句的結果被二級緩衝,預設值:對 select 元素為 true。 |
| timeout |
這個設定是在拋出異常之前,驅動程式等待資料庫返回請求結果的秒數。預設值為 unset(依賴驅動)。 |
| fetchSize |
這是嘗試影響驅動程式每次批量返回的結果行數和這個設定值相等。預設值為 unset(依賴驅動)。 |
| statementType |
STATEMENT,PREPARED 或 CALLABLE 的一個。這會讓 MyBatis 分別使用 Statement,PreparedStatement 或 CallableStatement,預設值:PREPARED。 |
| resultSetType |
FORWARD_ONLY,SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE 中的一個,預設值為 unset (依賴驅動)。 |
| databaseId |
如果配置了 databaseIdProvider,MyBatis 會載入所有的不帶 databaseId 或匹配當前 databaseId 的語句;如果帶或者不帶的語句都有,則不帶的會被忽略。 |
| resultOrdered |
這個設定僅針對嵌套結果 select 語句適用:如果為 true,就是假設包含了嵌套結果集或是分組了,這樣的話當返回一個主結果行的時候,就不會發生有對前面結果集的引用的情況。這就使得在擷取嵌套的結果集的時候不至於導致記憶體不夠用。預設值:false。 |
| resultSets |
這個設定僅對多結果集的情況適用,它將列出語句執行後返回的結果集並每個結果集給一個名稱,名稱是逗號分隔的。 |
Mybatis-mapper-xml-基礎