Spring Boot学习笔记(九)Spring Boot Jpa 与 Thymeleaf 实现增删改查

Spring Boot Jpa 与 Thymeleaf 实现增删改查

  • 源码链接:https://github.com/StephaineWYT/JpaThymeleafDemo
  • 初始化Spring项目 :https://start.spring.io/

    在这里插入图片描述

  • 解压后用IDEA打开,建立项目结构如下:

    在这里插入图片描述

  • pom.xml:

    先点击右下方提示:Enable-AutoImport

    <?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.1.7.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>wen</groupId>
        <artifactId>JpaThymeleafDemo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>JpaThymeleafDemo</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</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <optional>true</optional>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    
  • 数据库配置文件,记得根据自己的数据库账号密码以及url修改
    spring.datasource.url=jdbc:mysql://localhost:3306/jtl?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone = GMT
    spring.datasource.username=root
    spring.datasource.password=
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.jpa.properties.hibernate.hbm2ddl.auto=update
    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
    spring.jpa.show-sql=true
    spring.thymeleaf.cache=false
    
  • 注:存在上述jtl数据库即可,Spring Boot会根据实体类自动创建表
  • 实体类 model.User.java:
    package wen.JpaThymeleafDemo.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    
    @Entity
    public class User {
    
        @Id
        @GeneratedValue
        private long id;
    
        @Column(nullable = false, unique = true)
        private String username;
    
        @Column(nullable = false)
        private String password;
    
        @Column(nullable = false)
        private int age;
    
        public long getId() {
            return id;
        }
    
        public User setId(long id) {
            this.id = id;
            return this;
        }
     
     
        public String getUsername() {
            return username;
        }
    
        public User setUsername(String username) {
            this.username = username;
            return this;
        }
    
        public String getPassword() {
            return password;
        }
    
        public User setPassword(String password) {
            this.password = password;
            return this;
        }
    
        public int getAge() {
            return age;
        }
    
        public User setAge(int age) {
            this.age = age;
            return this;
        }
    }
    
  • UserRepository.java: 定义查和删两个接口用于service层调用
    package wen.JpaThymeleafDemo.repository;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    import wen.JpaThymeleafDemo.model.User;
    
    public interface UserRepository extends JpaRepository<User, Long> {
    
        User findById(long id);
    
        void deleteById(Long id);
    }
    
    
  • UserService.java: 定义两个增删改查的五个接口,用于controller层调用
    package wen.JpaThymeleafDemo.service;
    
    import wen.JpaThymeleafDemo.model.User;
    
    import java.util.List;
    
    public interface UserService {
    
        List<User> getUserList();
    
        User findUserById(long id);
    
        void save(User user);
    
        void edit(User user);
    
        void delete(long id);
    }
    
    
  • UserServiceImpl.java
    package wen.JpaThymeleafDemo.service.impl;
    
    import wen.JpaThymeleafDemo.model.User;
    import wen.JpaThymeleafDemo.repository.UserRepository;
    import wen.JpaThymeleafDemo.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserRepository userRepository;
    
        @Override
        public List<User> getUserList() {
            return userRepository.findAll();
        }
    
        @Override
        public User findUserById(long id) {
            return userRepository.findById(id);
        }
    
        @Override
        public void save(User user) {
            userRepository.save(user);
        }
    
        @Override
        public void edit(User user) {
            userRepository.save(user);
        }
    
        @Override
        public void delete(long id) {
            userRepository.deleteById(id);
        }
    }
    
    
  • UserController:
    package wen.JpaThymeleafDemo.web;
    
    import wen.JpaThymeleafDemo.model.User;
    import wen.JpaThymeleafDemo.service.UserService;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    @Controller
    public class UserController {
    
        @Resource
        UserService userService;
    
    
        @RequestMapping("/")
        public String index() {
            return "redirect:/list";
        }
    
        @RequestMapping("/list")
        public String list(Model model) {
            List<User> users = userService.getUserList();
            model.addAttribute("users", users);
            return "user/list";
        }
    
        @RequestMapping("/toAdd")
        public String toAdd() {
            return "user/userAdd";
        }
    
        @RequestMapping("/add")
        public String add(User user) {
            userService.save(user);
            return "redirect:/list";
        }
    
        @RequestMapping("/toEdit")
        public String toEdit(Model model, Long id) {
            User user = userService.findUserById(id);
            model.addAttribute("user", user);
            return "user/userEdit";
        }
    
        @RequestMapping("/edit")
        public String edit(User user) {
            userService.edit(user);
            return "redirect:/list";
        }
    
    
        @RequestMapping("/delete")
        public String delete(Long id) {
            userService.delete(id);
            return "redirect:/list";
        }
    }
    
    
  • 接下来配置前端文件:

    在这里插入图片描述

  • boostrap.css

    因为有8000多行,链接:https://pan.baidu.com/s/1-AlRxMV0tpkkeKMo0SYlKg
    提取码:r71q

  • list.html:
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>userList</title>
        <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
    </head>
    <body class="container">
    <br/>
    <h1>用户列表</h1>
    <br/><br/>
    <div class="with:80%">
        <table class="table table-hover">
            <thead>
            <tr>
                <th>id</th>
                <th>username</th>
                <th>password</th>
                <th>age</th>
                <th>edit</th>
                <th>delete</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="user : ${users}">
                <th scope="row" th:text="${user.id}">1</th>
                <td th:text="${user.username}">neo</td>
                <td th:text="${user.password}">Otto</td>
                <td th:text="${user.age}">6</td>
                <td><a th:href="@{/toEdit(id=${user.id})}">edit</a></td>
                <td><a th:href="@{/delete(id=${user.id})}">delete</a></td>
            </tr>
            </tbody>
        </table>
    </div>
    <div class="form-group">
        <div class="col-sm-2 control-label">
            <a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">add</a>
        </div>
    </div>
    
    </body>
    </html>
    
  • userAdd.html:
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>user</title>
        <link rel="stylesheet" th:href="@{/css/bootstrap.css}">
    </head>
    <body class="container">
    <br/>
    <h1>添加用户</h1>
    <br/><br/>
    <div class="with:80%">
        <form class="form-horizontal" th:action="@{/add}" method="post">
            <div class="form-group">
                <label for="username" class="col-sm-2 control-label">username</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="username" id="username" placeholder="username"/>
                </div>
            </div>
            <div class="form-group">
                <label for="password" class="col-sm-2 control-label">password</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" name="password" id="password" placeholder="password"/>
                </div>
            </div>
            <div class="form-group">
                <label for="age" class="col-sm-2 control-label">age</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="age" id="age" placeholder="age"/>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <input type="submit" value="Submit" class="btn btn-info"/>
                    &nbsp; &nbsp; &nbsp;
                    <input type="reset" value="Reset" class="btn btn-info"/>
                </div>
    
            </div>
        </form>
    </div>
    </body>
    </html>
    
    
  • userEdit.html:
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>user</title>
        <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
    </head>
    <body class="container">
    <br/>
    <h1>修改用户</h1>
    <br/><br/>
    <div class="with:80%">
        <form class="form-horizontal" th:action="@{/edit}" th:object="${user}" method="post">
            <input type="hidden" name="id" th:value="*{id}"/>
            <div class="form-group">
                <label for="username" class="col-sm-2 control-label">username</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="username" id="username" th:value="*{username}"
                           placeholder="username"/>
                </div>
            </div>
            <div class="form-group">
                <label for="password" class="col-sm-2 control-label">password</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" name="password" id="password" th:value="*{password}"
                           placeholder="password"/>
                </div>
            </div>
            <div class="form-group">
                <label for="age" class="col-sm-2 control-label">age</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="age" id="age" th:value="*{age}" placeholder="age"/>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <input type="submit" value="Submit" class="btn btn-info"/>
                    &nbsp; &nbsp; &nbsp;
                    <a href="/toAdd" th:href="@{/list}" class="btn btn-info">Back</a>
                </div>
    
            </div>
        </form>
    </div>
    </body>
    </html>
    
    
  • 启动项目

    在这里插入图片描述

  • 访问 http://localhost:8080/list

    在这里插入图片描述
    添加在这里插入图片描述
    查看
    在这里插入图片描述
    启动的时候如果Tests测试类疯狂报错,就删了吧,反正这个项目用不到
    下一篇:Spring Boot学习笔记(十)Spring Boot 集成 MyBatis —— 概念篇

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是 Spring Boot JPA 实现一对多增删改查的示例代码: 1. 创建实体类 ``` @Entity public class Parent { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true) private List<Child> children = new ArrayList<>(); // getters and setters } @Entity public class Child { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "parent_id") private Parent parent; // getters and setters } ``` 2. 创建 Repository 接口 ``` public interface ParentRepository extends JpaRepository<Parent, Long> { } ``` 3. 创建 Service 类 ``` @Service public class ParentService { @Autowired private ParentRepository parentRepository; public Parent save(Parent parent) { return parentRepository.save(parent); } public void delete(Long id) { parentRepository.deleteById(id); } public Parent findById(Long id) { return parentRepository.findById(id).orElse(null); } public List<Parent> findAll() { return parentRepository.findAll(); } } ``` 4. 创建 Controller 类 ``` @RestController @RequestMapping("/parents") public class ParentController { @Autowired private ParentService parentService; @PostMapping public Parent create(@RequestBody Parent parent) { return parentService.save(parent); } @PutMapping("/{id}") public Parent update(@PathVariable Long id, @RequestBody Parent parent) { Parent existingParent = parentService.findById(id); if (existingParent == null) { throw new RuntimeException("Parent not found"); } existingParent.setName(parent.getName()); existingParent.setChildren(parent.getChildren()); return parentService.save(existingParent); } @DeleteMapping("/{id}") public void delete(@PathVariable Long id) { parentService.delete(id); } @GetMapping("/{id}") public Parent findById(@PathVariable Long id) { return parentService.findById(id); } @GetMapping public List<Parent> findAll() { return parentService.findAll(); } } ``` 以上就是 Spring Boot JPA 实现一对多增删改查的示例代码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蛋饼双蛋不刷酱

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

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

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

打赏作者

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

抵扣说明:

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

余额充值