In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces how to use SqlSessionFactory and SqlSession in MyBatis. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.
The persistence solution of MyBatis is to liberate users from the original JDBC access. Users only need to define the SQL statements that need to be operated, and they can operate the persistence layer in an object-oriented way without paying attention to the underlying JDBC operations. There is no need for users to care about the acquisition of underlying database connection, the implementation of data access and transaction control, so that the application layer is extracted from the underlying JDBC/JTA API. Manage JDBC connections through configuration files and let MyBatis solve the implementation of persistence. The common objects in MyBatis are SqlSessionFactory and SqlSession. This article introduces the concept and use of the two.
- -
1. SqlSessionFactory
SqlSessionFactory is the key object of MyBatis. It is a compiled memory mirror of a single database mapping relationship. An instance of a SqlSessionFactory object can be obtained through the SqlSessionFactoryBuilder object class, while SqlSessionFactoryBuilder can build an instance of SqlSessionFactory from a XML configuration file or a pre-customized instance of Configuration. Every MyBatis application centers on an instance of a SqlSessionFactory object. At the same time, SqlSessionFactory is thread-safe, and once SqlSessionFactory is created, it should exist during application execution. Do not create repeatedly during the application run, it is recommended to use singleton mode. SqlSessionFactory is the factory where SqlSession is created.
The source code of the / / SqlSessionFactory interface is as follows: package org.apache.ibatis.session;import java.sql.Connection;public interface SqlSessionFactory {SqlSession openSession (); / / this method is most commonly used to create SqlSession objects. SqlSession openSession (boolean autoCommit); SqlSession openSession (Connection connection); SqlSession openSession (TransactionIsolationLevel level); SqlSession openSession (ExecutorType execType); SqlSession openSession (ExecutorType execType, boolean autoCommit); SqlSession openSession (ExecutorType execType, TransactionIsolationLevel level); SqlSession openSession (ExecutorType execType, Connection connection); Configuration getConfiguration ();}
II. SqlSession
SqlSession is the key object of MyBatis and exclusive for performing persistence operations, similar to Connection in JDBC. It is a single thread object for the interaction between the application and the persistence layer, and it is also the key object for MyBatis to perform persistence operations. the SqlSession object completely contains all the methods for performing SQL operations based on the database, and its underlying layer encapsulates JDBC connections, and the mapped SQL statements can be executed directly with SqlSession instances. Each thread should have its own instance of SqlSession. The instance of SqlSession cannot be shared, and SqlSession is also thread-unsafe. References to SqlSeesion instances should never be placed in a static field or even an instance field of a class. References to SqlSession instances should never be placed in any type of administrative scope, such as HttpSession objects in Servlet. It is important to turn off Session after using SqlSeesion, and be sure to use the finally block to close it.
/ / the source code of SqlSession API is as follows: package org.apache.ibatis.session;import java.io.Closeable;import java.sql.Connection;import java.util.List;import java.util.Map;import org.apache.ibatis.executor.BatchResult;public interface SqlSession extends Closeable {T selectOne (String statement); T selectOne (String statement, Object parameter); List selectList (String statement); List selectList (String statement, Object parameter); List selectList (String statement, Object parameter, RowBounds rowBounds); Map selectMap (String statement, String mapKey) Map selectMap (String statement, Object parameter, String mapKey); Map selectMap (String statement, Object parameter, String mapKey, RowBounds rowBounds); void select (String statement, Object parameter, ResultHandler handler); void select (String statement, ResultHandler handler); void select (String statement, Object parameter, RowBounds rowBounds, ResultHandler handler); int insert (String statement); int insert (String statement, Object parameter); int update (String statement); int update (String statement, Object parameter); int delete (String statement); int delete (String statement, Object parameter) Void commit (); void commit (boolean force); void rollback (); void rollback (boolean force); List flushStatements (); void close (); void clearCache (); Configuration getConfiguration (); T getMapper (Class type); Connection getConnection ();} III, SqlSessionFactory and SqlSession implementation process
The mybatis framework is mainly built around SqlSessionFactory, and the creation process is roughly as follows:
(1) define a Configuration object that contains data sources, transactions, mapper file resources, and settings, which affect database behavior properties.
(2) by configuring the object, you can create a SqlSessionFactoryBuilder object
(3) obtain an example of SqlSessionFactory through SqlSessionFactoryBuilder.
(4) the SqlSession instance of operation data can be obtained from the instance of SqlSessionFactory, through which the database can be operated.
And if you want to get SqlSessionFactory in the above way, you'd better use a similar configuration of mybatis-config.xml below. Here, the mybatis-config.xml configuration file has not been integrated with the Spring configuration file. If the mybaits configuration file and the Spring configuration file in the project have been integrated, it is estimated that the following code will make an error, because after the general integration of spring and mybatis, there is basically no need for the mybatis configuration file. The general practice will be the spring configuration file for the data sources and transactions configured in mybatis before. Then the following code does not get the necessary information when loading mybatis-config.xml, and there will be problems in the process of creation. So give a separate configuration file for mybatis-config.xml here.
The following line of code functions through the configuration file mybatis-config.xml, creates a SqlSessionFactory object, then generates SqlSession, and executes the SQL statement. The initialization of mybatis occurs in:
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder () .build (resourceAsStream)
If it is a configuration file after the integration of spring and mybaits, it is generally implemented in this way, the creation of SqlSessionFactory:
Give a specific process of using SqlSessionFactory and SqlSession objects:
Package com.cn.testIUserService;import java.io.IOException;import java.io.InputStream;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 com.cn.entity.User Public class MyBatisTest {public static void main (String [] args) {try {/ / read the mybatis-config.xml file InputStream resourceAsStream = Resources.getResourceAsStream ("mybatis-config.xml"); / / initialize mybatis and create an instance of SqlSessionFactory class SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (resourceAsStream); / / create session instance SqlSession session = sqlSessionFactory.openSession () / * * A lot of things are going to be done here, and so far, the goal has been achieved to get the SqlSession object. By calling the methods in SqlSession, * you can test the correctness between MyBatis and Dao layer interface methods, and of course you can do many other things, not to mention * / / inserting data User user = new User (); user.setC_password ("123"); user.setC_username (" 123") User.setC_salt ("123"); / / the first parameter is the fully qualified name of the method: location information + id session.insert (" com.cn.dao.UserMapping.insertUserInformation ", user) in the mapping file; / / commit transaction session.commit (); / / close session session.close () } catch (IOException e) {e.printStackTrace ();}
Give a detailed description of the content involved in the SqlSessionFactory and SqlSession creation process according to the above code.
Combined with the above SqlSessionFactory and SqlSession usage process and structure diagram, the methods involved are the following steps, and the methods in the source code are the following steps:
The first step is to read the configuration file of mybatis by SqlSessionFactoryBuilder, and then build a DefaultSqlSessionFactory to get SqlSessionFactory.
/ / the packages and methods involved in the source code are: / / the packages involved are: package org.apache.ibatis.session;// the first class is: SqlSessionFactoryBuilder, and the method designed to this class is the following: public SqlSessionFactory build (InputStream inputStream) {return build (inputStream, null, null) } public SqlSessionFactory build (InputStream inputStream, String environment, Properties properties) {try {/ / parses the configuration file through XMLConfigBuilder, and the parsed configuration-related information is encapsulated into a Configuration object XMLConfigBuilder parser = new XMLConfigBuilder (inputStream, environment, properties); / / then returns a DefaultSqlSessionFactory return build (parser.parse ());} catch (Exception e) {throw ExceptionFactory.wrapException ("Error building SqlSession.", e) } finally {ErrorContext.instance (). Reset (); try {inputStream.close ();} catch (IOException e) {/ / Intentionally ignore. Prefer previous error. } / / get DefaultSqlSessionFactory public SqlSessionFactory build (Configuration config) {return new DefaultSqlSessionFactory (config);} / / the second class is DefaultSqlSessionFactory, and the method involved is: public DefaultSqlSessionFactory (Configuration configuration) {this.configuration = configuration;}
Second, after you get the SqlSessionFactory, you can use the openSession of the SqlSessionFactory method to get the SqlSession object.
Private SqlSession openSessionFromDataSource (ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {Transaction tx = null; try {/ / get the configuration information related to Mybatis through the Confuguration object, the Environment object contains the configuration of the data source and transaction / / execType is the executor type, and / / SimpleExecutor-SIMPLE is defined in the configuration file. / / ReuseExecutor-the executor reuses the preprocessing statement (prepared statements) / / BatchExecutor-it is the batch executor final Environment environment = configuration.getEnvironment (); final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment (environment); tx = transactionFactory.newTransaction (environment.getDataSource (), level, autoCommit); / / defines the executor, which is the encapsulation of statement final Executor executor = configuration.newExecutor (tx, execType); / / finally returns a SqlSession return new DefaultSqlSession (configuration, executor, autoCommit) } catch (Exception e) {closeTransaction (tx); / / may have fetched a connection so lets call close () throw ExceptionFactory.wrapException ("Error opening session. Cause: "+ e, e);} finally {ErrorContext.instance () .reset ();}}
Once you have the SqlSession object, you can use the methods inside SqlSession for CRUD operations.
Note that the Connection object is created during the CURD operation after the SqlSession object is created. After a thorough search, you find the key code to get the Connection object in the ManagedTransaction class as follows:
Protected void openConnection () throws SQLException {if (log.isDebugEnabled ()) {log.debug ("Opening JDBC Connection");} / / there are three sources of dataSource, JndiDatasource,PooledDataSource,UnpooledDataSource. This.connection = this.dataSource.getConnection () is defined in the configuration file; if (this.level! = null) {this.connection.setTransactionIsolation (this.level.getLevel ());}}
The difference between PooledDataSource and UnPooledDataSource is that PooledDataSource uses connection pooling. Why use connection pooling? Because the process of creating a Connection object is equivalent to establishing a communication connection with the database at the bottom, it takes a lot of time to establish a communication connection, and often after we establish a connection (that is, after creating a Connection object), we execute a simple SQL statement, and then we have to throw it away, which is a very big waste of resources! The PooledDataSource proposed by mybatis to address this problem uses connection pooling. About the database connection pool knowledge points, you can own Baidu, here do not expand the introduction.
On how to use SqlSessionFactory and SqlSession in MyBatis to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.