阅读量:2
- 首先确保在pom.xml中添加spring和mybatis的依赖:
<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的SqlSessionFactory和MapperScannerConfigurer:
<!-- 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>
- 创建MyBatis的映射文件和Mapper接口:
<!-- 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的方法 }
- 创建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接口实现具体的数据库操作。