Spring boot + Mybatis 实现数据库的增删改查(CRUD)操作
在Spring Boot项目中使用MyBatis实现CRUD操作,首先需要添加相关依赖,配置数据源和MyBatis,然后定义Mapper接口和对应的XML映射文件。
- 添加依赖到
pom.xml
:
<dependencies>
<!-- Spring Boot相关依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- 数据库驱动,例如MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
- 配置
application.properties
或application.yml
:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
- 创建Mapper接口:
package com.example.demo.mapper;
public interface UserMapper {
User selectUserById(int id);
int insertUser(User user);
int updateUser(User user);
int deleteUserById(int id);
}
- 创建Mapper XML映射文件:
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="selectUserById" resultType="com.example.demo.model.User">
SELECT * FROM users WHERE id = #{id}
</select>
<insert id="insertUser" parameterType="com.example.demo.model.User">
INSERT INTO users(name, email) VALUES(#{name}, #{email})
</insert>
<update id="updateUser" parameterType="com.example.demo.model.User">
UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id}
</update>
<delete id="deleteUserById">
DELETE FROM users WHERE id = #{id}
</delete>
</mapper>
- 创建Service层:
package com.example.demo.service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(int id) {
return userMapper.selectUserById(id);
}
public int createUser(User user) {
return userMapper.i
评论已关闭