Mybatis Notes
Finally, I finished the month-long DDL battle and picked up my old love again.
In the next few days, I’ll go through the process: Mybatis -> Spring -> Spring MVC!
1. XML Configuration and Basic CRUD with XML
Maven XML Dependencies
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
</dependencies>
Mybatis Config XML
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
Mapper 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="xyz.aiinirii.mapper.UserMapper">
<select id="findAll" resultType="User">
SELECT * FROM user
</select>
</mapper>
2. Key Concepts
- SqlSessionFactory: Creates SqlSession instances
- SqlSession: Represents the connection to the database
- Mapper: Interface that defines database operations
3. CRUD Operations
// Select
List<User> users = sqlSession.selectList("findAll");
// Insert
sqlSession.insert("insertUser", user);
// Update
sqlSession.update("updateUser", user);
// Delete
sqlSession.delete("deleteUser", id);
Summary
Mybatis is a lightweight ORM framework that maps SQL statements to Java methods, providing flexibility and control over database operations.