Basic usage review:
SQL statements are stored in XML files or Java annotations. An example of MaBatis mapping (which uses Java interface and MyBatis annotation):
package org.mybatis.example;public interface BlogMapper { @Select("select * from Blog where id = #{id}") Blog selectBlog(int id);}Example of execution:
BlogMapper mapper = session.getMapper(BlogMapper.class);Blog blog = mapper.selectBlog(101);
SQL statements and mappings can also be externalized to an XML file:
<?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="org.mybatis.example.BlogMapper"> <select id="selectBlog" parameterType="int" resultType="Blog"> select * from Blog where id = #{id} </select></mapper>You can also use the MyBatis API to execute statements:
Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);For details, please refer to the user manual provided by the MyBatis website.
Integrate with Spring
MyBatis integrates with Spring Framework. Spring Framework allows MyBatis to participate in Spring transactions, creates MyBatis mappers and sessions, and injects them into other beans.
Here is a basic XML configuration example: a mapper is created and injected into the "BlogService" bean.
<bean id="sqlSessionFactory"> <property name="dataSource" ref="dataSource" /></bean><bean id="blogMapper"> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> <property name="mapperInterface" value="org.mybatis.example.BlogMapper" /></bean><bean id="blogService"> <property name="blogMapper" ref="blogMapper" /></bean>
Now calling MyBatis only requires calling one bean:
public class BlogServiceImpl implements BlogService { private BlogMapper blogMapper; public void setBlogMapper(BlogMapper blogMapper) { this.blogMapper = blogMapper; } public void doSomethingWithABlog(int blogId) { Blog blog = blogMapper.selectBlog(blogId); ... }} SqlSessionFactory
Each MyBatis application takes an instance of the SqlSessionFactory object as the core. SqlSessionFactory itself is created by SqlSessionFactoryBuilder. Generally speaking, in an application, a database will only correspond to a SqlSessionFactory, so we generally define SqlSessionFactory as a singleton pattern, or inject it through Spring, etc.
The methods for creating SqlSessionFactoryBuilder to create SqlSessionFactory are:
The main parameters designed by these methods are InputStream, environment, and properties, where InputStream is an input stream obtained from the configuration file; environment represents which environment you are currently using among the many environments configured in the configuration file, including data sources and transactions, and the default environment is used by default; using properties, MyBatis will load the corresponding properties or files, which can be used in the configuration file.
Building SqlSessionFactory from XML
private static SqlSessionFactory sqlSessionFactory = null; static { try { InputStream is = Resources.getResourceAsStream("config/mybatis_config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; }
The following is a basic structure of configuration files:
The configuration file of mybatis generally includes the following parts:
<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> Since MyBatis can configure multiple environments, you can specify a specific environment when creating a SqlSessionFactory to create a SqlSessionFactory. If you do not specify it, the default environment will be used.
transactionManager
There are two types of transaction managers in MyBatis (that is, type=”[JDBC|MANAGED]”):
JDBC This configuration directly and simply uses JDBC's commit and rollback settings. It relies on connections obtained from data sources to manage transaction scope.
MANAGED configuration does little. It never commits or rolls back a connection. And it allows the container to manage the entire life cycle of a transaction (such as the context of Spring or JEE application server) it closes the connection by default. However some containers don't want this, so if you need to stop it from the connection, set the closeConnection property to false.
dataSource
The dataSource element uses the basic JDBC data source interface to configure resources for JDBC connection objects.
Many MyBatis applications will configure the data source as shown in the examples. However, it is not necessary. You should know that in order to facilitate the use of lazy loading, data sources are necessary.
There are three built-in data source types (that is, type="???"):
UNPOOLED The implementation of this data source is to simply open and close the connection every time it is requested. It's a little slow, which is a great choice for simple applications, as it doesn't require timely available connections. Different databases also perform differently on this, so for some databases, it is not important to configure the data source, and this configuration is also idle. UNPOOLED type data source is only used to configure the following 5 properties:
As an option, you can pass the database driver properties. To do this, the prefix of the attribute starts with "driver." For example:
driver.encoding=UTF8
This will pass the value "UTF8" to pass the property "encoding", which is passed to the database driver through the DriverManager.getConnection(url,driverProperties) method.
POOLED This is an implementation of the data source connection pool for JDBC connection objects, which is used to avoid the necessary initial connection and authentication time when creating new connection instances. This is a popular method currently used by web applications to respond to requests quickly.
In addition to the above (UNPOOLED) attributes, there are many attributes that can be used to configure the POOLED data source:
Among them, JNDI data source configuration only requires two properties:
(1) The initial_context property is used to find the environment from the initial context (that is, initialContext.lookup(initial--context) . This is an optional property. If ignored, the data_source property will be searched again directly with initialContext as the background.
(2) data_source This is the path that references the context of the data source instance location. It will look for the environment returned by the initial_context query as the background. If initial_context does not return the result, it will look for the initial context as the environment directly.
Then there is a mapper. Mapper is used to map SQL statements. First, I need to tell mybatis where to find these SQL statements, that is, to specify the resource location.
<mappers> <mapper resource="com/tiantian/mybatis/model/BlogMapper.xml"/> </mappers>
Here is a simple configuration file I did during the testing process:
<?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="config/jdbc.properties"></properties> <typeAliases> <typeAlias alias="Blog" type="com.tiantian.mybatis.model.Blog"/> </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/tiantian/mybatis/model/BlogMapper.xml"/> </mappers> </configuration>
An external property file is imported into the above configuration file. The property introduction in the MyBatis configuration file can be directly included in the properties element, or it can be introduced from the outside using the properties element, or it can be passed in as a parameter properties when creating the SqlSessionFactory. Since properties in MyBatis configuration files can be introduced from so many places, it involves a priority issue, and MyBatis will look for them in the following order:
First, in the configuration file, the properties in the properties element body are read, and then the properties in the properties file introduced from the outside are read, which will overwrite the same properties read before. Finally, the properties in the properties passed in when creating the SqlSessionFactory are read, which will also overwrite the same properties before.
After having the SqlSessionFactory, you will get a specific SqlSession. In the process of using mybatis, every operation is inseparable from SqlSession, so it is very important to get a SqlSession. In addition, SqlSession cannot be shared and thread-insecure, so you should open one every time you need SqlSession and then close it after using it.
SqlSession session = sqlSessionFactory.openSession();
The methods of SqlSessionFactory Zhonghu District SqlSession are:
Their main differences are:
The default opensession method has no parameters, it will create a SqlSession with the following characteristics:
ExecutorType has three values:
The basic operations of mybatis are to add, delete, modify and check, namely insert, delete, update and select. When performing these basic operations, you can directly use SqlSession to access the mapping in the Mapper configuration file, or you can use the Mapper interface corresponding to the Mapper configuration file to perform operations, assuming that the parameters and return values of the methods defined in the Mapper interface must be the same as the parameters and return values defined in the Mapper configuration file. In addition, when using the Mapper interface, the corresponding SQL statements can be written in the Mapper configuration file, or they can be directly marked on the corresponding methods in the Mapper interface using the corresponding annotations. This will be seen in the following example code.
Here is a series of example codes:
First post a tool class to obtain SqlSessionFactory:
import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class Util { private static SqlSessionFactory sqlSessionFactory = null; static { try { InputStream is = Resources.getResourceAsStream("config/mybatis_config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } }
Mybatis configuration file:
<?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="config/jdbc.properties"></properties> <typeAliases> <typeAlias alias="Blog" type="com.tiantian.mybatis.model.Blog"/> </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/tiantian/mybatis/model/BlogMapper.xml"/> </mappers> </configuration>
BlogMapper.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.tiantian.mybatis.model.BlogMapper"> <!-- Add record--> <insert id="insertBlog" parameterType="Blog"> insert into t_blog(title,content,owner) values(#{title},#{content},#{owner}) </insert> <!-- Query a single record--> <select id="selectBlog" parameterType="int" resultType="Blog"> select * from t_blog where id = #{id} </select> <!-- Modify the record--> <update id="updateBlog" parameterType="Blog"> update t_blog set title = #{title},content = #{content},owner = #{owner} where id = #{id} </update> <!-- Query all records and query multiple records to return the result is a collection. resultType is not the collection type, but the type contained in the collection--> <select id="selectAll" resultType="Blog"> select * from t_blog </select> <!-- Fuzzy query--> <select id="fuzzyQuery" resultType="Blog" parameterType="java.lang.String"> select * from t_blog where title like "%"#{title}"%" </select> <!-- Delete record--> <delete id="deleteBlog" parameterType="int"> delete from t_blog where id = #{id} </delete> </mapper>Some issues that should be noted in SQL mapping statements:
Blog.java
package com.tiantian.mybatis.model; public class Blog { private int id; private String title; private String content; private String owner; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } @Override public String toString() { return "id: " + id + ", title: " + title + ", content: " + content + ", owner: " + owner; } }
BlogMapper.java
package com.tiantian.mybatis.model; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; /** * The following operations 1 writes SQL in the configuration file, while operations 2 directly indicate the SQL statement to be executed with annotations* Because the full name of the mapper is the same as the namespace in the BlogMapper.xml file, it cannot be included here* Use annotations to define a map with the same name as the BlogMapper.xml file* @author andy * */ public interface BlogMapper { public Blog selectBlog(int id); @Select("select * from t_blog where id = #{id}") public Blog selectBlog2(int id); public void insertBlog(Blog blog); @Insert("insert into t_blog(title,content,owner) values(#{title},#{content},#{owner})") public void insertBlog2(Blog blog); public void updateBlog(Blog blog); @Update("update t_blog set title=#{title},content=#{content},owner=#{owner} where id=#{id}") public void updateBlog2(Blog blog); public void deleteBlog(int id); @Delete("delete from t_blog where id = #{id}") public void deleteBlog2(int id); public List<Blog> selectAll(); @Select("select * from t_blog") public List<Blog> selectAll2(); public List<Blog> fuzzyQuery(String title); @Select("select * from t_blog where title like /"%/"#{title}/"%/"") public List<Blog> fuzzyQuery2(String title); }
Test1.java
package com.tiantian.mybatis.test; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import com.tiantian.mybatis.model.Blog; import com.tiantian.mybatis.util.Util; /** * This series of operations is by writing SQL in the configuration file, and then using SqlSession for operation* @author andy * */ public class Test1 { /** * Add record*/ @Test public void testInsertBlog() { SqlSession session = Util.getSqlSessionFactory().openSession(); Blog blog = new Blog(); blog.setTitle("Chinese"); blog.setContent("How many dreams have been hidden in the wind and rain for five thousand years"); blog.setOwner("Daily"); session.insert("com.tiantian.mybatis.model.BlogMapper.insertBlog", blog); session.commit(); session.close(); } /** * Query a single record*/ @Test public void testSelectOne() { SqlSession session = Util.getSqlSessionFactory().openSession(); Blog blog = (Blog)session.selectOne("com.tiantian.mybatis.model.BlogMapper.selectBlog", 8); System.out.println(blog); session.close(); } /** * Modify record*/ @Test public void testUpdateBlog() { SqlSession session = Util.getSqlSessionFactory().openSession(); Blog blog = new Blog(); blog.setId(7);//The id of the Blog that needs to be modified blog.setTitle("Chinese 2");//Modify Title blog.setContent("yellow face, black eyes, unchanged smile");//Modify Content blog.setOwner("day 2");//Modify Owner session.update("com.tiantian.mybatis.model.BlogMapper.updateBlog", blog); session.commit(); session.close(); } /** * Query all records*/ @Test public void testSelectAll() { SqlSession session = Util.getSqlSessionFactory().openSession(); List<Blog> blogs = session.selectList("com.tiantian.mybatis.model.BlogMapper.selectAll"); for (Blog blog:blogs) System.out.println(blog); session.close(); } /** * Fuzzy query*/ @Test public void testFuzzyQuery() { SqlSession session = Util.getSqlSessionFactory().openSession(); String title = "China"; List<Blog> blogs = session.selectList("com.tiantian.mybatis.model.BlogMapper.fuzzyQuery", title); for (Blog blog:blogs) System.out.println(blog); session.close(); } /** * Delete record*/ @Test public void testDeleteBlog() { SqlSession session = Util.getSqlSessionFactory().openSession(); session.delete("com.tiantian.mybatis.model.BlogMapper.deleteBlog", 8); session.commit(); session.close(); } }
Test2.java
package com.tiantian.mybatis.test; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import com.tiantian.mybatis.model.Blog; import com.tiantian.mybatis.model.BlogMapper; import com.tiantian.mybatis.util.Util; /** * This series of operations is to write SQL statements in the configuration file, * and then operate through the corresponding Mapper interface* @author andy * */ public class Test2 { /** * Add record*/ @Test public void testInsertBlog() { SqlSession session = Util.getSqlSessionFactory().openSession(); Blog blog = new Blog(); blog.setTitle("Chinese"); blog.setContent("How many dreams have been hidden in the wind and rain for five thousand years"); blog.setOwner("Daily"); BlogMapper blogMapper = session.getMapper(BlogMapper.class); blogMapper.insertBlog(blog); session.commit(); session.close(); } /** * Query single record*/ @Test public void testSelectOne() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); Blog blog = blogMapper.selectBlog(7); System.out.println(blog); session.close(); } /** * Modify record*/ @Test public void testUpdateBlog() { SqlSession session = Util.getSqlSessionFactory().openSession(); Blog blog = new Blog(); blog.setId(9);// The id of the Blog that needs to be modified blog.setTitle("Chinese 2");// Modify Title blog.setContent("yellow face, black eyes, unchanged smile");// Modify Content blog.setOwner("day 2");// Modify Owner BlogMapper blogMapper = session.getMapper(BlogMapper.class); blogMapper.updateBlog(blog); session.commit(); session.close(); } /** * Query all records*/ @Test public void testSelectAll() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); List<Blog> blogs = blogMapper.selectAll(); for (Blog blog : blogs) System.out.println(blog); session.close(); } /** * Fuzzy query*/ @Test public void testFuzzyQuery() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); String title = "China"; List<Blog> blogs = blogMapper.fuzzyQuery(title); for (Blog blog : blogs) System.out.println(blog); session.close(); } /** * Delete record*/ @Test public void testDeleteBlog() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); blogMapper.deleteBlog(10); session.commit(); session.close(); } }
Test3.java
package com.tiantian.mybatis.test; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import com.tiantian.mybatis.model.Blog; import com.tiantian.mybatis.model.BlogMapper; import com.tiantian.mybatis.util.Util; /** * This series of operations is performed using the Mapper interface * , but its corresponding SQL statement is defined on the corresponding method in the Mapper through the corresponding * annotation * @author andy * */ public class Test3 { /** * New record*/ @Test public void testInsert() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); Blog blog = new Blog(); blog.setTitle("title2"); blog.setContent("content2"); blog.setOwner("owner2"); blogMapper.insertBlog2(blog); session.commit(); session.close(); } /** * Find a single record*/ @Test public void testSelectOne() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); Blog blog = blogMapper.selectBlog2(1); System.out.println(blog); session.close(); } /** * Find multiple records, return the result as a collection*/ @Test public void testSelectAll() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); List<Blog> blogs = blogMapper.selectAll2(); for (Blog blog:blogs) System.out.println(blog); session.close(); } /** * Modify a record*/ @Test public void testUpdate() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); Blog blog = new Blog(); blog.setId(3); blog.setTitle("title3"); blog.setContent("content3"); blog.setOwner("owner3"); blogMapper.updateBlog2(blog); session.commit(); session.close(); } /** * Delete record*/ @Test public void testDelete() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); blogMapper.deleteBlog2(5); session.commit(); session.close(); } @Test public void testFuzzyQuery() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); List<Blog> blogs = blogMapper.fuzzyQuery2("China"); for (Blog blog:blogs) System.out.println(blog); session.close(); } }Corresponding table creation statement:
CREATE TABLE `t_blog` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `content` varchar(255) DEFAULT NULL, `owner` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) )