Springboot+Mybatis实现最简单的增删改查
以下是一个简单的Spring Boot + MyBatis实现最基本增删改查的示例。
- 首先,在
pom.xml
中添加Spring Boot和MyBatis依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 数据库驱动依赖,以MySQL为例 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</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
- 创建一个实体类
User
:
public class User {
private Integer id;
private String name;
private Integer age;
// 省略getter和setter方法
}
- 创建一个Mapper接口
UserMapper
:
@Mapper
public interface UserMapper {
int insertUser(User user);
int deleteUserById(Integer id);
int updateUser(User user);
User selectUserById(Integer id);
}
- 创建对应的Mapper XML文件
UserMapper.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">
<insert id="insertUser" parameterType="User">
INSERT INTO user(name, age) VALUES (#{name}, #{age})
</insert>
<delete id="d
评论已关闭