用springboot mybatis写一个增删改查

首先,在pom.xml文件中添加Spring Boot、MyBatis和MySQL的相关依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
        <groupId>org.mybatis.spring.bootgroupId>
        <artifactId>mybatis-spring-boot-starterartifactId>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <scope>runtimescope>
    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语句:


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并实现增删改查的功能:

@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或其他工具来测试增删改查的功能了。

你可能感兴趣的:(JavaWeb项目,spring,boot,mybatis,后端)