Building upon foundational MyBatis knowledge, this guide demonstrates how to implement Create, Read, Update, and Delete (CRUD) operations using MyBatis with a clean and maintainable structure.
The implementation requires updates to three core components: the DAO enterface, its corresponding XML mapper, and test cases. All CRUD methods are consolidated in a single file for clear comparison.
DAO Interface
package com.dao;
import com.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getAllUsers();
User getUserById(String name);
int insertUser(User user);
int updateUser(User user);
int deleteUser(String name);
}
Note that method parameters and return types are carefully chosen to match database operations. The identifier used here is name, not a numeric ID, as reflected in the SQL logic.
Mapper XML Configuration
<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="com.dao.UserDao">
<select id="getAllUsers" resultType="com.pojo.User">
SELECT * FROM jdbc1.users
</select>
<select id="getUserById" resultType="com.pojo.User" parameterType="string">
SELECT * FROM jdbc1.users WHERE name = #{name}
</select>
<insert id="insertUser" parameterType="com.pojo.User">
INSERT INTO jdbc1.users (name, pwd, number, danweixinxi)
VALUES (#{name}, #{pwd}, #{number}, #{danweixinxi})
</insert>
<update id="updateUser" parameterType="com.pojo.User">
UPDATE jdbc1.users
SET pwd = #{pwd}, number = #{number}, danweixinxi = #{danweixinxi}
WHERE name = #{name}
</update>
<delete id="deleteUser" parameterType="string">
DELETE FROM jdbc1.users WHERE name = #{name}
</delete>
</mapper>
The XML mapper defines SQL statements mapped to each DAO method. Placeholders like #{name} safely inject values from Java objects or primitives.
Test Cases
package com.dao;
import com.pojo.User;
import com.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void testSelectAll() {
try (SqlSession session = MyBatisUtils.getSqlSession()) {
UserDao dao = session.getMapper(UserDao.class);
List<User> users = dao.getAllUsers();
users.forEach(System.out::println);
}
}
@Test
public void testSelectById() {
try (SqlSession session = MyBatisUtils.getSqlSession()) {
UserDao dao = session.getMapper(UserDao.class);
User user = dao.getUserById("科泽华");
System.out.println(user);
}
}
@Test
public void testInsert() {
try (SqlSession session = MyBatisUtils.getSqlSession()) {
UserDao dao = session.getMapper(UserDao.class);
User newUser = new User("科泽华", "shagou", "niuniuniu", "studgouwo");
int rows = dao.insertUser(newUser);
if (rows > 0) {
System.out.println("Insert successful");
}
session.commit();
}
}
@Test
public void testUpdate() {
try (SqlSession session = MyBatisUtils.getSqlSession()) {
UserDao dao = session.getMapper(UserDao.class);
User updatedUser = new User("科泽华", "嗡嗡嗡", "不牛不牛", "不在狗窝");
int rows = dao.updateUser(updatedUser);
if (rows > 0) {
System.out.println("Update successful");
}
session.commit();
}
}
@Test
public void testDelete() {
try (SqlSession session = MyBatisUtils.getSqlSession()) {
UserDao dao = session.getMapper(UserDao.class);
int rows = dao.deleteUser("Null");
if (rows > 0) {
System.out.println("Delete successful");
}
session.commit();
}
}
}
A critical detail in write operations (INSERT, UPDATE, DELETE) is explicitly calling session.commit(). Without it, changes appear successful in the application but are not persisted to the database due to MyBatis’s transaction managemant.
Using try-with-resources ensures proper session closure, enhancing robustness. The mapper-based approach (getMapper()) is preferred over string-based statement execution to type safety and maintainability.