用SpringBoot整合mybatis实现简单增删改查操作的代码
时间: 2024-05-09 19:17:13 浏览: 74
好的,以下是使用SpringBoot整合mybatis实现简单增删改查操作的代码示例:
1. 首先在pom.xml中添加依赖:
```xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
```
2. 在application.properties中配置数据库相关信息:
```properties
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# Mybatis配置
mybatis.mapper-locations=classpath*:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity
```
3. 创建实体类和Mapper接口:
```java
// User实体类
public class User {
private Long id;
private String name;
private Integer age;
// getter和setter方法省略
}
```
```java
// UserMapper接口
public interface UserMapper {
User selectById(Long id);
List<User> selectAll();
void insert(User user);
void update(User user);
void delete(Long id);
}
```
4. 在resources/mapper目录下创建UserMapper.xml文件,定义SQL语句:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!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">
<resultMap id="BaseResultMap" type="com.example.demo.entity.User">
<id column="id" property="id" jdbcType="BIGINT" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<select id="selectById" resultMap="BaseResultMap">
SELECT id, name, age FROM user WHERE id = #{id}
</select>
<select id="selectAll" resultMap="BaseResultMap">
SELECT id, name, age FROM user
</select>
<insert id="insert">
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
<update id="update">
UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
<delete id="delete">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
```
5. 在Service中调用Mapper接口:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Long id) {
return userMapper.selectById(id);
}
public List<User> getAllUser() {
return userMapper.selectAll();
}
public void addUser(User user) {
userMapper.insert(user);
}
public void updateUser(User user) {
userMapper.update(user);
}
public void deleteUser(Long id) {
userMapper.delete(id);
}
}
```
最后,启动应用程序即可进行增删改查操作。
阅读全文