table of Contents
Five, databaseIdProvider label
One, properties tag
Function: You can import external resource files.
There are two attributes:
resource
: Import resource files under the classpathurl
: Introduce resources under the network or disk path
We modify yesterday’s case. First, we create a properties resource file: dbconfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root
Then we use <properties>
tags to introduce it in the global configuration file :
<properties resource="dbconfig.properties"></properties>
Then we can use ${name}
to modify the configuration of the data source in the global configuration file , which name
is the name of the configuration in the resource file:
<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>
The modified global configuration file is as follows:
<?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>
<!--
mybatis可以使用properties来引入外部properties配置文件的内容
属性:
resource:引入类路径下的资源
url:引入网络或者磁盘路径下的资源
-->
<properties resource="dbconfig.properties"></properties>
<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>
<!-- 将我们写好的sql映射文件一定要注册到全局配置文件中 -->
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
</configuration>
Run yesterday's test code:
package com.cerr.mybatis;
import com.cerr.mybatis.dao.EmployeeMapper;
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.Test;
import java.io.IOException;
import java.io.InputStream;
import static org.junit.Assert.*;
public class MyBatisTest {
//获取SQLSessionFactory
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void test1() throws IOException {
//获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
//获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
//获取接口的实现类对象:会为接口自动的创建一个代理对象,代理对象去执行增删改查
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
//调用方法
Employee employee = employeeMapper.getEmpById(1);
//打印
System.out.println(employee);
}finally {
//关闭
sqlSession.close();
}
}
}
If you can query normally, the configuration is successful.
Two, the settings tab
This is a very important adjustment setting in MyBatis, they will change the runtime behavior of MyBatis.
In our tb1_employee data table, there is a field name last_name, and the attribute name of this field name in the corresponding bean is lastName. If it select * from tb1_employee ;
is impossible to assign a value to the lastName attribute during query , and we now want to make it assignable, So we can use settings
a parameter in the tag mapUnderscoreToCamelCase
to achieve this. This parameter indicates whether to enable automatic camel case naming rule mapping, that is, a similar mapping from the database column name A_COLUMN to the Java attribute name aColumn.
We now set its parameter to true
indicate that the automatic camel case naming rule mapping is turned on.
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
The complete configuration information is as follows:
<?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="dbconfig.properties"></properties>
<!--
包含有很多重要的设置项
setting:用来设置每一个设置项目
name:设置项名
value:设置项值
-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<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>
<!-- 将我们写好的sql映射文件一定要注册到全局配置文件中 -->
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
</configuration>
The configuration in the EmployeeMapper.xml file is as follows:
<?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.cerr.mybatis.dao.EmployeeMapper">
<select id="getEmpById" resultType="com.cerr.mybatis.Employee">
select * from tb1_employee where id = #{id}
</select>
</mapper>
After running, the lastName
attribute can be successfully assigned.
For the specific remaining parameters, please refer to the official documentation.
Three, typeAliases label
Alias processor, you can alias our Java types. There are three ways of aliasing:
- Alias a type
- Batch aliases for all classes under a certain package
- In the case of batch processing, give a new alias for a class
Use typeAlias to alias a type
To alias a type, the tag has two attributes:
type
: Specify the full class name of the type to be aliasedalias
: Specify a new alias. If it is not written, the default alias will be used. The default alias is type lowercase (but uppercase is also OK, because it is not case sensitive).
<typeAliases>
<typeAlias type="com.cerr.mybatis.Employee" alias="emp"/>
</typeAliases>
The above example gives our com.cerr.mybatis.Employee the alias emp. When we need to use this class next, we don't need to write the full class name, but use emp directly.
Use package to alias all classes in a package in batches
There is an attribute:: name属性
Specify the package name (each class of the current package and all descendant packages below has a default alias, the default is the class name in lowercase (but uppercase is also OK, because it is not case sensitive)
<typeAliases>
<package name="com.cerr.mybatis"/>
</typeAliases>
The above example has com.cerr.mybatis
aliases for all classes and descendant packages under our package. The aliases are lowercase class names, for example com.cerr.mybatis
.
But this is not very convenient for us. If there is a sub-package under the package that has a class with the same class name as the package, there will be a conflict, so we package
can use the third one when we use it.
Use @Alias
annotations to alias
This must be used in the configuration file package
.
In the case of batch aliasing, @Alias
annotations can be used to specify a new alias for a certain type.
package com.cerr.mybatis;
import org.apache.ibatis.type.Alias;
@Alias("emp")
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
The above code used @Alias
to name the class emp
.
Four, the environments label
Mybatis can configure a variety of environments, you can deafult
specify the use of a certain environment through properties, and you can quickly switch the environment.
<environments>
The sub-tag inside <environment>
can be configured with a specific environment information, and id represents the unique identifier of the current environment. <environment>
Must have <transactionManager>
and <dataSource>
label.
<transactionManager>
label
<transactionManager>
The label is the transaction manager and has an type
attribute that specifies the type of transaction manager. There are two parameter values that can be specified:
JDBC
:useJdbcTransactionFactory
MANAGED
:useManagedTransactionFactory
You can also use a custom transaction manager: as long as you implement the TransactionFactory interface, type is specified as the full class name of the implementation class.
<dataSource>
label
<dataSource>
Is the data source. There is an type
attribute and three parameter values can be specified:
UNPOOLED
: Do not use the connection pool, that is, useUnpooledDataSourceFactory
POOLED
: Use connection pool, that is, usePooledDataSourceFactory
JNDI
: Use JNDI technology, that is, useJndiDataSourceFactory
You can also use a custom data source: the implementation DataSourceFactory
interface type
is the full class name of the class that implements the interface.
Example: Configure database information
<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>
Five, databaseIdProvider label
Support multiple database vendors.
<databaseIdProvider type="DB_VENDOR"></databaseIdProvider>
In the above code type="DB_VENDOR"
in DB_VENDOR
refers to VendorDatabaseIdProvider
the role of database vendor identification is obtained (own drive), myBatis can be performed depending on different databases sql statement.
There is also a subtag inside <property>
, which is used to alias the database vendor's logo.
E.g:
<databaseIdProvider type="DB_VENDOR">
<!-- 为不同的数据库厂商起别名 -->
<property name="MySQL" value="mysql"/>
<property name="Oracle" value="oracle"/>
<property name="SQL Server" value="sqlserver"/>
</databaseIdProvider>
Then you need to configure the database statement in the local configuration file.
Configure it in the local configuration file
The above code can get the ID of the database vendor and alias the ID of the database vendor. Then we need to identify which sentence corresponds to which database in the label in the local configuration file.
There is an databaseId
attribute in the statement tag in the partial configuration file , which can specify which database is used.
For example, we can define a query statement in multiple ways to support different databases.
EmployeeMapper.xml
Configure in the 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="com.cerr.mybatis.dao.EmployeeMapper">
<select id="getEmpById" resultType="com.cerr.mybatis.Employee">
select * from tb1_employee where id = #{id}
</select>
<select id="getEmpById" resultType="com.cerr.mybatis.Employee" databaseId="mysql">
select * from tb1_employee where id = #{id}
</select>
<select id="getEmpById" resultMap="com.cerr.mybatis.Employee" databaseId="oracle">
select * from employees where id = #{id}
</select>
</mapper>
After this configuration, MyBatis will automatically execute different SQL statements according to the database environment you use.
Six, mappers tags
Register the sql mapping in the global configuration, each one mapper
is to register a sql mapping.
For <mapper>
tags, there are three attributes:
resource
: Refer to the sql mapping file under the class path. If it is under the package, write the package name in,/
instead of using it between package levels.
. For example, thecom.mapper
package should be written ascom/mapper
url
: Refer to the sql mapping file under the network or disk pathclass
: Reference interface.
Put the xml configuration file in resource
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
Reference registration interface based on class
-
There must be a sql mapping file, and the mapping file name must be the same as the interface name and placed in the same directory as the interface.
- There is no sql mapping file, all sql is written on the interface using annotations.
package com.cerr.mybatis.dao;
import com.cerr.mybatis.Employee;
import org.apache.ibatis.annotations.Select;
public interface EmployeeMapperAnnotation {
@Select("select * from tb1_employee where id = #{id}")
public Employee getEmpById(Integer id);
}
<mappers>
<mapper class="com.cerr.mybatis.dao.EmployeeMapperAnnotation"/>
</mappers>
For some more important, complex dao interfaces, we use SQL mapping files; for some simple dao interfaces, we can directly use annotations for rapid development.
Use <package>
bulk registration
We can use <package>
to batch register sql mapping files under a certain package. It applies to both annotation-based interfaces and non-annotated interfaces, but the non-annotated interfaces must be placed in the same package as the corresponding xml file, which is the same as the first case where the registered interface is referenced based on class.
<mappers>
<!-- 批量注册 -->
<package name="com.cerr.mybatis.dao"/>
</mappers>