首先,在pom.xml文件中添加Spring Boot、MyBatis和MySQL的相关依赖:
<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>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
接下来,创建一个实体类User.java代表用户信息:
public class User {
private Long id;
private String username;
private String password;
// 省略getter和setter方法
}
然后,创建一个Mapper接口UserMapper.java用于定义增删改查的方法:
public interface UserMapper {
User selectUserById(Long id);
List<User> selectAllUsers();
void insertUser(User user);
void updateUser(User user);
void deleteUserById(Long id);
}
接着,在resources目录下创建一个mapper目录,并在该目录下创建UserMapper.xml文件,配置具体的SQL语句:
<?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.mapper.UserMapper">
<resultMap id="userResultMap" type="com.example.entity.User">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
</resultMap>
<select id="selectUserById" resultMap="userResultMap">
SELECT * FROM user WHERE id = #{id}
</select>
<select id="selectAllUsers" resultMap="userResultMap">
SELECT * FROM user
</select>
<insert id="insertUser">
INSERT INTO user (username, password) VALUES (#{username}, #{password})
</insert>
<update id="updateUser">
UPDATE user SET username = #{username}, password = #{password} WHERE id = #{id}
</update>
<delete id="deleteUserById">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
最后,创建一个UserController.java作为控制器,注入UserMapper并实现增删改查的功能:文章来源:https://www.toymoban.com/news/detail-794066.html
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id) {
return userMapper.selectUserById(id);
}
@GetMapping("/users")
public List<User> getAllUsers() {
return userMapper.selectAllUsers();
}
@PostMapping("/users")
public void addUser(@RequestBody User user) {
userMapper.insertUser(user);
}
@PutMapping("/users/{id}")
public void updateUser(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
userMapper.updateUser(user);
}
@DeleteMapping("/users/{id}")
public void deleteUser(@PathVariable Long id) {
userMapper.deleteUserById(id);
}
}
现在,你可以启动Spring Boot应用,使用Postman或其他工具来测试增删改查的功能了。文章来源地址https://www.toymoban.com/news/detail-794066.html
到了这里,关于用springboot mybatis写一个增删改查的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!