MyBatis Introduction#
Learning Objectives#
- [Application] Quick start with MyBatis
- [Application] CRUD operations with MyBatis
- [Master] Overview of MyBatis core configuration files
1. Introduction to MyBatis#
1.1 Raw JDBC Operations (Querying Data)#
1.2 Raw JDBC Operations (Inserting Data)#
1.3 Analysis of Raw JDBC Operations#
The problems with raw JDBC development are as follows:
- Frequent creation and release of database connections waste system resources and affect system performance.
- SQL statements are hard-coded in the code, making it difficult to maintain. In practical applications, SQL changes are likely, and changes in SQL require changes in Java code.
- During query operations, it is necessary to manually encapsulate the data in the result set into entities. During insert operations, it is necessary to manually set the entity data to the placeholders in the SQL statement.
Solutions to the above problems:
- Use a database connection pool to initialize connection resources.
- Extract SQL statements into XML configuration files.
- Use low-level technologies such as reflection and introspection to automatically map properties and fields between entities and tables.
1.4 What is MyBatis#
MyBatis is an excellent Java-based persistence framework that encapsulates JDBC, allowing developers to focus only on the SQL statements themselves without spending effort on loading drivers, creating connections, creating statements, and other complex processes.
MyBatis configures various statements to be executed through XML or annotations and maps them to the final SQL statements generated through Java objects and dynamic parameters in the statements.
Finally, the MyBatis framework executes the SQL and maps the results to Java objects before returning them. It uses ORM concepts to solve the problem of mapping entities to databases, encapsulates JDBC, and shields the underlying access details of the JDBC API, allowing us to perform persistent operations on the database without dealing with the JDBC API.
1.5 MyBatis Architecture#
2. Quick Start with MyBatis#
2.1 MyBatis Development Steps#
MyBatis official website: http://www.mybatis.org/mybatis-3/
MyBatis development steps:
- Add MyBatis dependencies.
- Create the user data table.
- Write the User entity class.
- Write the mapping file UserMapper.xml.
- Write the core file SqlMapConfig.xml.
- Write the test class.
2.2 Environment Setup#
1. Import MyBatis dependencies and other related dependencies
<!-- MyBatis dependency -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- MySQL driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- Unit testing dependency -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Logging dependency -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
2. Create the user data table
drop table if EXISTS user;
## User
CREATE TABLE `user` (
`uid` INT AUTO_INCREMENT ,
`username` VARCHAR(20) DEFAULT NULL,
`password` VARCHAR(20) DEFAULT NULL,
PRIMARY KEY (`uid`)
);
INSERT INTO `user` VALUES (NULL,'wc001','888888'),
(NULL,'xq001','888888'),
(NULL,'xb001','888888');
3. Write the User entity
public class User {
private int id;
private String username;
private String password;
// Omitted get and set methods
}
4. Write the UserMapper mapping 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="userMapper">
<select id="findAll" resultType="com.summer.domain.User">
select * from User
</select>
</mapper>
5. Write the MyBatis core file
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- Load mapping files -->
<mappers>
<mapper resource="UserMapper.xml" />
</mappers>
</configuration>
2.3 Write Test Code#
@Test
public void test1() throws IOException {
// Load MyBatis main configuration file
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// Get session factory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// Create session
SqlSession session = sqlSessionFactory.openSession();
// Execute operation
List<User> users = session.selectList("userMapper.findAll");
// Release resources
session.close();
System.out.println(users);
}
To view the execution information of SQL statements, configure the logging file log4j.properties
in the resources directory.
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.com.summer.test=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
2.4 Knowledge Summary#
MyBatis development steps:
- Add MyBatis dependencies.
- Create the user data table.
- Write the User entity class.
- Write the mapping file UserMapper.xml.
- Write the core file SqlMapConfig.xml.
- Write the test class.
3. Overview of MyBatis Mapping Files#
4. MyBatis CRUD Operations#
4.1 MyBatis Insert Data Operation#
1. Write the UserMapper mapping file
<insert id="save" parameterType="com.summer.domain.User" >
insert into user values (null,#{username},#{password});
</insert>
2. Write the code to insert the User entity
// Add
@Test
public void test2() throws IOException {
User user = new User();
user.setUsername("如花");
user.setPassword("888");
// Load MyBatis main configuration file
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// Get session factory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// Create session
SqlSession session = sqlSessionFactory.openSession();
// Execute operation
int i = session.insert("userMapper.save",user);
// Release resources
session.commit();
session.close();
System.out.println(i);
}
3. Notes on Insert Operations
- Use the insert tag for insert statements.
- Specify the data type to be inserted using the parameterType attribute in the mapping file.
- Use the #{entity property name} syntax to reference property values in the SQL statement.
- The API used for insert operations is sqlSession.insert("namespace.id", entity object);
- Since insert operations involve changes to the database data, the sqlSession object must explicitly commit the transaction using sqlSession.commit().
4.2 MyBatis Update Data Operation#
1. Write the UserMapper mapping file
<update id="update" parameterType="com.summer.domain.User" >
update user set username = #{username} , password = #{password} where uid =#{uid}
</update>
2. Write the code to update the User entity
// Update
@Test
public void test3() throws IOException {
User user = new User();
user.setUid(1);
user.setUsername("如花2222");
user.setPassword("888");
// Load MyBatis main configuration file
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// Get session factory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// Create session
SqlSession session = sqlSessionFactory.openSession();
// Execute operation
int i = session.update("userMapper.update",user);
// Commit transaction
session.commit();
// Release resources
session.close();
System.out.println(i);
}
3. Notes on Update Operations
- Use the update tag for update statements.
- The API used for update operations is sqlSession.update("namespace.id", entity object);
4.3 MyBatis Delete Data Operation#
1. Write the UserMapper mapping file
<delete id="delete" parameterType="java.lang.Integer" >
delete from user where uid = #{uid}
</delete>
2. Write the code to delete data
// Delete
@Test
public void test4() throws IOException {
// Load MyBatis main configuration file
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// Get session factory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// Create session
SqlSession session = sqlSessionFactory.openSession();
// Execute operation
int i = session.delete("userMapper.delete",1);
// Commit transaction
session.commit();
// Release resources
session.close();
System.out.println(i);
}
3. Notes on Delete Operations
- Use the delete tag for delete statements.
- Use the #{any string} syntax in the SQL statement to reference the single parameter passed.
- The API used for delete operations is sqlSession.delete("namespace.id", Object);
5. Overview of MyBatis Core Configuration Files#
5.1 Hierarchical Relationship of MyBatis Core Configuration Files#
5.2 Common MyBatis Configuration Analysis#
1. environments tag
Configuration of database environments, supporting multiple environment configurations
2. mapper tag
The purpose of this tag is to load mappings, and there are several loading methods:
- Use relative class path resource references, for example:
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
- Use fully qualified resource locators (URLs), for example:
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
- Use the fully qualified class name of the mapper interface to annotate the mapper interface, for example:
<mapper class="org.mybatis.builder.AuthorMapper"/>
- Register all mapper interfaces under a specified package, for example:
<package name="org.mybatis.builder"/>
3. Properties tag
4. typeAliases tag
Type aliases are short names set for Java types. The original configuration is as follows:
<select id="findAll" resultType="com.summer.pojo.User">
select * from user
</select>
Configure typeAliases to define an alias for com.summer.pojo.User as User:
<typeAliases>
<typeAlias type="com.summer.pojo.User" alias="user"></typeAlias>
</typeAliases>
Subsequent mapper.xml can then use the alias:
<select id="findAll" resultType="User">
select * from user
</select>
The above is a custom alias, and the MyBatis framework has already set up some commonly used type aliases for us.
5.3 Knowledge Summary#
Common configurations in core configuration files:
- properties tag: This tag can load external properties files.
<properties resource="jdbc.properties"></properties>
- typeAliases tag: Set type aliases.
<typeAlias type="com.summer.domain.User" alias="user"></typeAlias>
- mappers tag: Load mapping configurations.
<mapper resource="com/summer/mapper/UserMapping.xml"></mapper>