04---springboot实现增删改查

1、配置文件

application.yml

server:
  port: 8081
spring:
  mvc:
    path match:
      matching-strategy: ant_path_matcher
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/management?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8
mybatis:
  type-aliases-package: com.xqh.entity
  mapper-locations: classpath:/mapper/*.xml






  • mybatis的配置:一个是扫描实体类的位置;一个是扫描mapper的位置
  • 出现BUG:Invalid bound statement (not found): com.xqh.demo.mapper.UserMapper.update] with root cause启动报错,原因就是没有设置扫描mapper包,加上 mapper-locations: classpath:/mapper/*.xml就可以了!

2、mapper

UserMapper.java

package com.xqh.mapper;
import com.xqh.entity.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;
@Mapper
@Repository
public interface UserMapper {
    //查出所有数据
    List<User>findAll();

    int insert(User user);

    int delete(@Param("id") Integer id);

    int update(User user);
}

  • 实现增删改查的接口

3、UserMapper.xml

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xqh.mapper.UserMapper">
    <insert id="insert" parameterType="User">
        INSERT into user(username,password,nickname,email,phone,address) VALUES (#{username},#{password},#{nickname},#{email},#{phone},#{address})
    </insert>

    <delete id="delete" parameterType="int">
        delete from user where id=#{id}
    </delete>

<!--    要写动态sql,因为很多情况是只修改其中几项,而不是全部修改。如果传过来的参数不为空才修改,为空就保持原样-->

    <update id="update" parameterType="User">

        update user
        <set>
            <if test="username!=null">
                username=#{username}
            </if>
            <if test="password!=null">
                password=#{password}
            </if>
            <if test="nickname!=null">
                nickname=#{nickname}
            </if>
            <if test="email!=null">
                email=#{email}
            </if>
            <if test="phone!=null">
                phone=#{phone}
            </if>
            <if test="address!=null">
                address=#{address}
            </if>

        </set>
        <where>
            id=#{id}
        </where>

    </update>
    <select id="findAll" resultType="User">
        select * from user
    </select>

</mapper>

  • 将sql语句写在mapper里(resource下新建mapper包),UserMapper.xml
  • 对于更新操作update,因为我们不是每次都要改所有的参数,有时候只会改其中几个,而另外的则传的是null,所以要实现没改的地方还用原来的,就要用动态sql语句

4、Service层

UserService.java

package com.xqh.service;
import com.xqh.entity.User;
import com.xqh.mapper.UserMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<User>findAll(){
        return userMapper.findAll();
    };

    public int delete(@Param("id") int id){
        return userMapper.delete(id);
    };


    public int save(User user){
        if (user.getId()==null){  //user没有id,则表示是新增,否则为更新
            return userMapper.insert(user);
        }else {
            return userMapper.update(user);
        }
    }
}

  • 更新和添加操作可以在同一个方法里实现,因为都是更新一个user对象,所以只需要用一个if语句,来判断传入的user对象的id是否存在,有id则是原本就有的数据—执行修改操作;如果id为null,则是新的数据,那么执行添加

5、Controller层

UserController.java

package com.xqh.controller;
import com.xqh.entity.User;
import com.xqh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController  //返回json
@RequestMapping("/user")   //加前缀,这下面的所有接口都要加/user前缀
public class UserController {
    @Autowired
    private UserService userService;

    //查询所有
    @GetMapping
    public List<User> index(){
        return userService.findAll();
    }

    //插入和修改操作  , 需要外界发送数据,用post
    @PostMapping
    public Integer save(@RequestBody User user){
        return userService.save(user);
    }

    //删除
    @DeleteMapping("/{id}")
    public Integer delete(@PathVariable Integer id){
        return userService.delete(id);
    }


}

6、运行测试接口

运行主程序,打开swagger页面 localhost:8081/swagger-ui.html ,测试接口,增删改查,成功操作数据库即完成

在这里插入图片描述

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot是一款非常流行的开源框架,它提供了许多便捷的工具和组件,可以快速搭建一个基于Spring的Web应用程序。 在Spring Boot中,实现增删改查可以使用Spring Data JPA和Spring MVC等组件来完成。 首先需要定义一个实体类,用于表示数据库中的表。然后使用Spring Data JPA中的Repository来对该实体类进行CRUD操作。在Controller中,通过接收HTTP请求参数来调用相应的Repository方法,从而实现对数据的增删改查。 下面是一个简单的示例: 1.定义实体类 ```java @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "age") private Integer age; // getter和setter方法省略 } ``` 2.定义Repository接口 ```java @Repository public interface UserRepository extends JpaRepository<User, Long> { } ``` 3.编写Controller ```java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/") public List<User> getAllUsers() { return userRepository.findAll(); } @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userRepository.findById(id).orElse(null); } @PostMapping("/") public User createUser(@RequestBody User user) { return userRepository.save(user); } @PutMapping("/{id}") public User updateUser(@PathVariable Long id, @RequestBody User user) { User existingUser = userRepository.findById(id).orElse(null); if (existingUser != null) { existingUser.setName(user.getName()); existingUser.setAge(user.getAge()); return userRepository.save(existingUser); } return null; } @DeleteMapping("/{id}") public void deleteUser(@PathVariable Long id) { userRepository.deleteById(id); } } ``` 4.相关问题:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zero摄氏度

感谢鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值