SoFunction
Updated on 2025-03-10

Basic steps and mechanisms for MyBatis connection database configuration

Preface

MyBatis is a popular persistence layer framework that binds SQL statements, stored procedures, and Java methods by using XML or annotations, thus avoiding handwriting a large amount of JDBC code and manually setting parameters and result sets. Here are the basic steps and mechanisms for connecting to a database with MyBatis:

MyBatis source code version: 3.5.16

Example

<environments default="development">  
    <environment >  
        <transactionManager type="JDBC"/>  
        <dataSource type="POOLED">  
            <property name="driver" value="${}"/>  
            <property name="url" value="${}"/>  
            <property name="username" value="${}"/>  
            <property name="password" value="${}"/>  
        </dataSource>  
    </environment>  
</environments>

1. Read the configuration file

MyBatis byResourcesClass reads configuration files. Configuration files are usually in XML format, such as

Key Code

String resource = "";
Reader reader = (resource)

2. Parsing the configuration file

SqlSessionFactoryBuilderuseXMLConfigBuilderParse the configuration file and convert the XML configuration into a Java object.

Key Code

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);

XMLConfigBuilder Source Code Snippet

private void parseConfiguration(XNode root) {  
  try {  
    // issue #117 Read the attribute first    propertiesElement(("properties"));  
    Properties settings = settingsAsProperties(("settings"));  
    loadCustomVfsImpl(settings);  
    loadCustomLogImpl(settings);  
    typeAliasesElement(("typeAliases"));  
    pluginsElement(("plugins"));  
    objectFactoryElement(("objectFactory"));  
    objectWrapperFactoryElement(("objectWrapperFactory"));  
    reflectorFactoryElement(("reflectorFactory"));  
    settingsElement(settings);  
    // read it after objectFactory and objectWrapperFactory issue #631  
    environmentsElement(("environments"));  
    databaseIdProviderElement(("databaseIdProvider"));  
    typeHandlersElement(("typeHandlers"));  
    mappersElement(("mappers"));  
  } catch (Exception e) {  
    throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);  
  }  
}

XMLConfigBuilderparse XML configuration and generateConfigurationObject.

3. Create SqlSessionFactory

ConfigurationThe object contains all configuration information, including environment configuration, data source configuration, etc.SqlSessionFactoryBuilderuseConfigurationcreateDefaultSqlSessionFactory

Key Code

public SqlSessionFactory build(Configuration config) {  
  return new DefaultSqlSessionFactory(config);  
}

4. Establish a database connection

DefaultSqlSessionFactoryCreateSqlSessionWhen, throughEnvironmentConfiguration andDataSourceGet the database connection.

DefaultSqlSessionFactory Source Code Snippet

public SqlSession openSession() {  
  return openSessionFromDataSource((), null, false);  
}

openSessionFromDataSourceIn the method,DataSourceUsed to obtain database connections.

Key Code

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level,  
    boolean autoCommit) {  
  //Environment configuration  final Environment environment = ();  
  //Business Factory  final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);  
  //Create a transaction  Transaction tx = ((), level, autoCommit);  
  //Create an executor  final Executor executor = (tx, execType);  
  //Return to SqlSession  return new DefaultSqlSession(configuration, executor, autoCommit);
}

5. Data source configuration

DataSourceConfigure inIn the file, throughDataSourceFactoryCreate a specific data source instance.

Key Code

// Obtain the data source factoryString type = ("type");  
Properties props = ();  
DataSourceFactory factory = (DataSourceFactory) resolveClass(type).getDeclaredConstructor().newInstance();  
(props);    
// Get the data sourceDataSource dataSource = ();

Summarize

The steps to connect to the MyBatis database include:

  • Read configuration files:passResourcesClass reads XML files.
  • Parse configuration files:useXMLConfigBuilderparse XML, generateConfigurationObject.
  • Create SqlSessionFactory:useSqlSessionFactoryBuilderandConfigurationcreateDefaultSqlSessionFactory
  • Establish a database connectionDefaultSqlSessionFactorycreateSqlSession,useDataSourceGet the database connection.

The above is the detailed content of the basic steps and mechanism of MyBatis connection database configuration. For more information about MyBatis connection database configuration, please pay attention to my other related articles!