Learn http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html today. About the use of SQL statements for Mapper.xml.
Project path: Https://github.com/chenxing12/l4mybatis
First, prepare the environment.
1. Create Project
On the parent project, right-click New Model->maven->mybatis-mapper.
Fill 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> & lt;groupid>com.test</groupid> <version>1.0-SNAPSHOT</version> </parent> <modelv Ersion>4.0.0</modelversion> <artifactId>mytatis-mapper</artifactId> <dependencies> <dependency> <groupId>org.mybatis</groupId> <ARTIFACTID>MYBATIS</ARTIFAC tid> </dependency> <dependency> <groupId>mysql</groupId> &L t;artifactid>mysql-connector-java</artifactid> </dependency> <dependency> &L T;groupid>junit</groupid> <artifactId>junit</artifactId> </dependency> <dependency> <grou pid>log4j</groupid> <artifactId>log4j</artifactId> </dependency> <d Ependency> <groupId>org.slf4j</groupId> <artifactid>slf4j-log4j12</artifacti d> </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> & lt;/includes> <filtering>true</filtering> </resource> </resources > </build></project>
Add log4j.properties under Resources:
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
Add Mybatis-config.xml under Resources:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.d TD "><configuration> <properties resource=" db.properties "/> <typeAliases> <package Nam E= "Com.test.mapper.model"/> </typeAliases> <environments default= "Development" > <environmen T 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=" Passwo Rd "value=" ${jdbc.password} "/> </dataSource> </environment> </environments> & lt;mappers> <mapper resource= "Com.test.mapper.mapper/personmapper.xml"/> </mappers></configuration>
Add db.properties under Resources:
#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
Create a person table in the database mybatis:
/*navicat MySQL Data transfersource server : Localhostsource server Version:50605source Host : Localhost:3306so Urce 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 (one) ' 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 ');
Create a com.test.mapper.mapper/personmapper.xml under resources:
<?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>
Create a new Com.test.mapper.dao.PersonMapper.java under Java:
Package Com.test.mapper.dao;import java.util.hashmap;/** * Created by Miaorf on 2016/7/6. */public interface Personmapper { HashMap selectperson (int id);}
Added under 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 environment:
Create a com.test.mapper.dao.PersonMapperTest under test:
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); }}
run:
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 was not Availa ble in this environment.2016-07-06 22:23:32,131 DEBUG [Org.apache.ibatis.io.VFS]-Class not found:org.jboss.vfs.Virtual file2016-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.Per Son 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
Query statements. is responsible for stitching query statements and mapping out the query results. In the example above:
<select id= "Selectperson" parametertype= "int" resulttype= "HashMap" > select * from person WHERE id = #{id}</ Select>
- The ID of this statement is Selectperson, which is the name of the method corresponding to the Mapper interface.
- ParameterType is an input parameter of type int.
- Resulttype indicates that the query result is mapped to HashMap
- #{id} is a placeholder equivalent to a question mark in the SQL statement in JDBC that uses preparedstatement, which means that the parameter value with the parameter name ID will replace the location.
Notice that the namespace of the mapper.xml is pointing to the corresponding mapper interface:
<mapper namespace= "Com.test.mapper.dao.PersonMapper" >
The methods in the Mapper interface correspond to the IDs in the Mapper.xml one by one. Therefore, the Mapper interface for this query's node corresponds to the following method:
Public interface Personmapper { HashMap selectperson (int id);}
In fact, the optional parameters of the Select node are as follows:
<select id= "Selectperson" parametertype= "int" parametermap= "deprecated" resulttype= "HashMap " resultmap=" Personresultmap " flushcache=" false " usecache=" true " timeout=" 10000 " fetchsize = "Statementtype=" " PREPARED" resultsettype= "Forward_only" >
The document explains the meaning of each parameter:
Select Attributes
Properties |
Description |
Id |
A unique identifier in the namespace that can be used to refer to this statement. |
ParameterType |
The fully qualified name or alias of the parameter class that will pass in the statement. This property is optional because MyBatis can infer the parameters of the specific incoming statement through Typehandler, and the default value is unset. |
Parametermap |
This is a deprecated method that references an external parametermap. Use inline parameter mapping and ParameterType properties. |
Resulttype |
The fully qualified name or alias of the class of the expected type returned from this statement. Note that if it is a collection case, it should be the type that the collection can contain, not the collection itself. Use Resulttype or Resultmap, but not at the same time. |
Resultmap |
A named reference to an external resultmap. The mapping of result sets is the most powerful feature of MyBatis, and a good understanding of it is that many complex mapping scenarios can be solved. Use Resultmap or Resulttype, but not at the same time. |
Flushcache |
Setting it to true will cause both the local cache and the level two cache to be emptied whenever the statement is invoked, with the default value: False. |
UseCache |
Setting it to true causes the result of this statement to be cached by level two, the default: True for the SELECT element. |
Timeout |
This setting is the number of seconds that the driver waits for the database to return the result of the request before throwing an exception. The default value is unset (dependent driver). |
Fetchsize |
This is an attempt to affect the number of results per batch returned by the driver and the value of this setting is equal. The default value is unset (dependent driver). |
StatementType |
One of the statement,prepared or callable. This allows MyBatis to use statement,preparedstatement or CallableStatement, respectively, with the default value: PREPARED. |
ResultsetType |
One of the forward_only,scroll_sensitive or scroll_insensitive, the default value is unset (dependent driver). |
DatabaseId |
If Databaseidprovider,mybatis is configured, all statements without databaseId or matching the current databaseId are loaded, and if a statement with or without is present, it is ignored. |
Resultordered |
This setting applies only to nested results SELECT statements: If True, the assumption is that nested result sets or groupings are included, so that when a main result row is returned, there is no case of a reference to the preceding result set. This makes it possible to get a nested result set without causing enough memory. Default value:false. |
ResultSets |
This setting applies only to multi-result sets, which list the result sets returned after the statement executes and each result set to a name, separated by commas. |
Mybatis-mapper-xml-Foundation