<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
</dependencies>
<!-- MyBatis配置文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper" />
</bean>
<!-- com/example/mapper/UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectUserById" resultType="com.example.model.User">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="insertUser" parameterType="com.example.model.User">
INSERT INTO user(name, age) VALUES(#{name}, #{age})
</insert>
<!-- 同理,添加update和delete的SQL語句 -->
</mapper>
// 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的方法
}
// com/example/model/User.java
package com.example.model;
public class User {
private int id;
private String name;
private int age;
// 省略getter和setter方法
}
// 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接口實現具體的數據庫操作。