- 首先确保在pom.xml中添加spring和mybatis的依赖:
org.springframework spring-context 5.2.5.RELEASE org.mybatis mybatis 3.5.3
- 配置mybatis的SqlSessionFactory和MapperScannerConfigurer:
- 创建MyBatis的映射文件和Mapper接口:
INSERT INTO user(name, age) VALUES(#{name}, #{age})
// com/example/mapper/UserMapper.java package com.example.mapper; import com.example.model.User; public interface UserMapper { User selectUserById(int id); void insertUser(User user); // 添加update和delete的方法 }
- 创建User类作为实体类:
// com/example/model/User.java package com.example.model; public class User { private int id; private String name; private int age; // 省略getter和setter方法 }
- 编写Service类调用Mapper接口实现增删改查操作:
// com/example/service/UserService.java package com.example.service; import com.example.mapper.UserMapper; import com.example.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserMapper userMapper; public User getUserById(int id) { return userMapper.selectUserById(id); } public void addUser(User user) { userMapper.insertUser(user); } // 添加update和delete的方法 }
至此,就完成了Spring整合MyBatis实现增删改查操作的基本步骤。通过配置MyBatis的SqlSessionFactory和MapperScannerConfigurer,以及编写Mapper接口和映射文件,再通过Service类调用Mapper接口实现具体的数据库操作。