快速入门Springboot之增删改查

一、创建SpringBoot项目

1、项目目录

2、pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.steven</groupId>
    <artifactId>springboot-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <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.2.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--阿里数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!--        获取页面session对象request对象response对象 HttpServletXXX jar包-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
        <!--        json转换工具包-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!-- 如果不配置fork,devtools就不会起作用,devtools是前端开发工具-->
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

3、application.yml文件

spring:
  web:
    resources:
      static-locations: classpath:/static/,classpath:/templates/
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url:地址
    username: 账号
    password: 密码
    driver-class-name: com.mysql.cj.jdbc.Driver
    #普通浏览器只能get和post请求,
    #所以如果需要其他的请求方式,需要这个,然后隐藏起来
  mvc:
    hiddenmethod:
      filter:
        enabled: true
  devtools:
    restart:
      enabled: true #设置开启热部署
  freemarker:
    cache: false #页面不加载缓存,修改即使生效
mybatis:
  configuration:
    map-underscore-to-camel-case: true #下划线驼峰设置
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   # 打印SQL语句

4、user表

建表语句

CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `password` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

5、User实体类

@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    public User(Integer id,String username,String password) {
        this.id=id;
        this.username=username;
        this.password=password;
    }
    public User() {
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

6、Dao层(也就是mapper)

@Mapper
public interface UserMapper {
    //查询全部
    @Select("select * from user")
    List<User> findAll();
    //新增数据
    @Insert("insert into user (username,password) values (#{username},#{password})")
    public int save(User user);
    //删除数据
    @Delete("delete from user where id=#{id}")
    public int delete(int id);
    //根据id查找
    @Select("select * from user where id=#{id}")
    public User get(int id);
    //更新数据
    @Update("update user set username=#{username},password=#{password} where id=#{id}")
    public int update(User user);
}

7、Service层

public interface UserService {
    //查询全部
    List<User> findAll();
    //新增数据
    int save(User user);
    //删除数据
    Integer delete(int id);
    //根据id查找
    User get(int id);
    //更新数据
    int update(User user);
}

8、Service实现类

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }
    @Override
    public int save(User user) {
        return userMapper.save(user);
    }
    @Override
    public Integer delete(int id) {
        return userMapper.delete(id);
    }
    @Override
    public User get(int id) {
        return userMapper.get(id);
    }
    @Override
    public int update(User user) {
        return userMapper.update(user);
    }
}

9、Controller层

//控制层,导入Service层
@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/index.html")
    public String userList(Map<String, List> result) {
        List<User> Users=userService.findAll();
        result.put("users",Users);
        return "index";
    }
    //新增数据
    @PostMapping("/add")
    public String save(User user) {
        userService.save(user);
        //表示重置index.html界面并且跳转到index.html界面
        return "redirect:/index.html";
    }
    //删除数据,本来需要使用DeleteMapping,但是由于没有界面可以隐藏,所以这里就直接写了RequestMapping
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable Integer id, HttpServletResponse servletResponse) throws IOException {
        userService.delete(id);
        System.out.println("delete方法执行");
        return "redirect:/index.html";
    }
    //根据id进行修改
    @GetMapping("/updatePage/{id}")
    public String updatePage(Model model, @PathVariable int id){
        User users = userService.get(id);
        model.addAttribute("users",users);
        //表示跳转到modifie,html界面
        return "modifie";
    }
    @PutMapping("/update")
    public String updateUser(Model model, User user, HttpServletRequest request) {
        String id = request.getParameter("id");
        User userById = userService.get(Integer.parseInt(id));
        userService.update(user);
        System.out.println(user);
        return "redirect:/index.html";
    }
}

10、add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加用户</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div style="width:600px;height:100%;margin-left:270px;">
    <form action="/add" method="post">
<!--        form-control给input添加这个class后就会使用bootstrap自带的input框-->
        用户名:<input class="form-control" type="text" th:value="${username}" name="username"><br>
        <!--注意参数的拼接-->
        密 码:<input class="form-control" type="text" th:value="${password}" name="password"><br>
        <button class="btn btn-primary btn-lg btn-block">保存</button>
    </form>
</div>
</body>
</html>

11、index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<style>
    a{
        color: #ffffff;
    }
    h1{
        /*文字对齐*/
        text-align: center;
    }
</style>
<body>
<h1>spring-boot</h1>
<!--table-striped:斑马线格式,table-bordered:带边框的表格,table-hover:鼠标悬停高亮的表格-->
<table class="table table-striped table-bordered table-hover text-center">
    <thead>
    <tr style="text-align:center">
<!--        th标签定义html表格中的表头单元格-->
        <th>编号</th>
        <th>姓名</th>
        <th>密码</th>
        <th>操作</th>
    </tr>
    </thead>
<!--tr标签定义html表格中的所有行-->
<!--    遍历集合,如果被遍历的变量users为null或者不存在,则不会进行遍历,也不会报错-->
    <tr th:each="user:${users}">
<!--        td标签定义html表格中的标准单元格-->
        <td th:text="${user.id}"></td>
        <td th:text="${user.username}"></td>
        <td th:text="${user.password}"></td>
        <td>
<!--         a标签用来定义超链接 href表示超链接-->
            <a class="btn btn-primary" th:href="@{'/updatePage/'+${user.id}}">更改</a>
            <a class="btn btn-danger" th:href="@{'/delete/'+${user.id}}">删除</a>
        </td>
    </tr>
</table>
<button class="btn btn-block" ><a href="/add.html">添加用户</a></button>
</body>
</html>

12、modifie.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>修改用户</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div style="width:600px;height:100%;margin-left:270px;">
    <form action="/update" method="post">
    <!-- rest风格中的更新是put请求,
    所以这块先使用post请求,然后隐藏起来改为put请求-->
        <input name="_method" type="hidden" value="put">
        ID:<input class="form-control"  type="text" th:value="${users.id}" name="id"><br>
        用户名:<input class="form-control" type="text" th:value="${users.username}" name="username"><br>
        密 码:<input class="form-control" type="text" th:value="${users.password}" name="password"><br>
        <button class="btn btn-primary btn-lg btn-block" type="submit">提交</button>
    </form>
</div>
</body>
</html>

都敲完以后运行起来,直接在网址那里填localhost:8080/index.html即可,随后点击更新会自动跳转到更新界面,如有问题请私信留言!

或者直接访问springboot官方自行学习:Spring Boot

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
很抱歉,作为AI语言模型,我不能提供完整的代码,但我可以给你一个大致的思路: 首先,你需要创建一个Spring Boot项目,并在其中添加一个Controller类,用于处理HTTP请求。 在Controller类中,你可以定义四个方法,分别对应增、删、改、查操作。例如: ``` @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userService.getUserById(id); } @PostMapping("/") public User createUser(@RequestBody User user) { return userService.createUser(user); } @PutMapping("/{id}") public User updateUser(@PathVariable Long id, @RequestBody User user) { return userService.updateUser(id, user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable Long id) { userService.deleteUser(id); } } ``` 在上面的代码中,我们定义了四个方法,分别对应根据ID查询用户、创建用户、更新用户和删除用户。这些方法都是通过调用UserService类中的方法来实现的。 在UserService类中,你可以定义类似下面的方法: ``` @Service public class UserService { @Autowired private UserRepository userRepository; public User getUserById(Long id) { return userRepository.findById(id).orElseThrow(() -> new UserNotFoundException()); } public User createUser(User user) { return userRepository.save(user); } public User updateUser(Long id, User user) { User existingUser = userRepository.findById(id).orElseThrow(() -> new UserNotFoundException()); existingUser.setName(user.getName()); existingUser.setEmail(user.getEmail()); return userRepository.save(existingUser); } public void deleteUser(Long id) { userRepository.deleteById(id); } } ``` 在上面的代码中,我们定义了四个方法,分别对应根据ID查询用户、创建用户、更新用户和删除用户。这些方法都是通过调用UserRepository类中的方法来实现的。 UserRepository类是一个JpaRepository,它提供了许多内置的方法,例如save、findById、deleteById等。你可以像这样定义它: ``` @Repository public interface UserRepository extends JpaRepository<User, Long> { } ``` 最后,你需要定义一个User类,它用于表示一个用户的信息。例如: ``` @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // getters and setters } ``` 以上就是一个简单的增删改查的代码结构。当然,实际的实现可能会更加复杂,但这应该可以帮助你入门

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

南方的晨露

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值