这篇文章介绍如何使用jpa和thymeleaf做一个增删改查的示例。

快速上手

配置文件

pom包配置

pom包里面添加jpa和thymeleaf的相关包引用

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-data-jpa</artifactId>
  12. </dependency>
  13. <dependency>
  14. <groupId>mysql</groupId>
  15. <artifactId>mysql-connector-java</artifactId>
  16. </dependency>

在application.properties中添加配置

  1. spring.datasource.url=jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
  2. spring.datasource.username=root
  3. spring.datasource.password=root
  4. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  5. spring.jpa.properties.hibernate.hbm2ddl.auto=update
  6. spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
  7. spring.jpa.show-sql= true
  8. spring.thymeleaf.cache=false

其中propertiesspring.thymeleaf.cache=false是关闭thymeleaf的缓存,不然在开发过程中修改页面不会立刻生效需要重启,生产可配置为true。

在项目resources目录下会有两个文件夹:static目录用于放置网站的静态内容如css、js、图片;templates目录用于放置项目使用的页面模板。

启动类

启动类需要添加Servlet的支持

  1. @SpringBootApplication
  2. public class JpaThymeleafApplication extends SpringBootServletInitializer {
  3. @Override
  4. protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
  5. return application.sources(JpaThymeleafApplication.class);
  6. }
  7. public static void main(String[] args) throws Exception {
  8. SpringApplication.run(JpaThymeleafApplication.class, args);
  9. }
  10. }

数据库层代码

实体类映射数据库表

  1. @Entity
  2. public class User {
  3. @Id
  4. @GeneratedValue
  5. private long id;
  6. @Column(nullable = false, unique = true)
  7. private String userName;
  8. @Column(nullable = false)
  9. private String password;
  10. @Column(nullable = false)
  11. private int age;
  12. ...
  13. }

继承JpaRepository类会自动实现很多内置的方法,包括增删改查。也可以根据方法名来自动生成相关sql,具体可以参考:springboot(五):spring data jpa的使用-spring-data-jpa%E7%9A%84%E4%BD%BF%E7%94%A8.html)

  1. public interface UserRepository extends JpaRepository<User, Long> {
  2. User findById(long id);
  3. Long deleteById(Long id);
  4. }

业务层处理

service调用jpa实现相关的增删改查,实际项目中service层处理具体的业务代码。

  1. @Service
  2. public class UserServiceImpl implements UserService{
  3. @Autowired
  4. private UserRepository userRepository;
  5. @Override
  6. public List<User> getUserList() {
  7. return userRepository.findAll();
  8. }
  9. @Override
  10. public User findUserById(long id) {
  11. return userRepository.findById(id);
  12. }
  13. @Override
  14. public void save(User user) {
  15. userRepository.save(user);
  16. }
  17. @Override
  18. public void edit(User user) {
  19. userRepository.save(user);
  20. }
  21. @Override
  22. public void delete(long id) {
  23. userRepository.delete(id);
  24. }
  25. }

Controller负责接收请求,处理完后将页面内容返回给前端。

  1. @Controller
  2. public class UserController {
  3. @Resource
  4. UserService userService;
  5. @RequestMapping("/")
  6. public String index() {
  7. return "redirect:/list";
  8. }
  9. @RequestMapping("/list")
  10. public String list(Model model) {
  11. List<User> users=userService.getUserList();
  12. model.addAttribute("users", users);
  13. return "user/list";
  14. }
  15. @RequestMapping("/toAdd")
  16. public String toAdd() {
  17. return "user/userAdd";
  18. }
  19. @RequestMapping("/add")
  20. public String add(User user) {
  21. userService.save(user);
  22. return "redirect:/list";
  23. }
  24. @RequestMapping("/toEdit")
  25. public String toEdit(Model model,Long id) {
  26. User user=userService.findUserById(id);
  27. model.addAttribute("user", user);
  28. return "user/userEdit";
  29. }
  30. @RequestMapping("/edit")
  31. public String edit(User user) {
  32. userService.edit(user);
  33. return "redirect:/list";
  34. }
  35. @RequestMapping("/delete")
  36. public String delete(Long id) {
  37. userService.delete(id);
  38. return "redirect:/list";
  39. }
  40. }
  • return "user/userEdit"; 代表会直接去resources目录下找相关的文件。
  • return "redirect:/list"; 代表转发到对应的controller,这个示例就相当于删除内容之后自动调整到list请求,然后再输出到页面。

页面内容

list列表

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8"/>
  5. <title>userList</title>
  6. <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
  7. </head>
  8. <body class="container">
  9. <br/>
  10. <h1>用户列表</h1>
  11. <br/><br/>
  12. <div class="with:80%">
  13. <table class="table table-hover">
  14. <thead>
  15. <tr>
  16. <th>#</th>
  17. <th>User Name</th>
  18. <th>Password</th>
  19. <th>Age</th>
  20. <th>Edit</th>
  21. <th>Delete</th>
  22. </tr>
  23. </thead>
  24. <tbody>
  25. <tr th:each="user : ${users}">
  26. <th scope="row" th:text="${user.id}">1</th>
  27. <td th:text="${user.userName}">neo</td>
  28. <td th:text="${user.password}">Otto</td>
  29. <td th:text="${user.age}">6</td>
  30. <td><a th:href="@{/toEdit(id=${user.id})}">edit</a></td>
  31. <td><a th:href="@{/delete(id=${user.id})}">delete</a></td>
  32. </tr>
  33. </tbody>
  34. </table>
  35. </div>
  36. <div class="form-group">
  37. <div class="col-sm-2 control-label">
  38. <a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">add</a>
  39. </div>
  40. </div>
  41. </body>
  42. </html>

效果图:

Spring Boot Jpa  Thymeleaf 增删改查示例 - 图1

<tr th:each="user : ${users}"> 这里会从controler层model set的对象去获取相关的内容,th:each表示会循环遍历对象内容。

其实还有其它的写法,具体的语法内容可以参考这篇文章:springboot(四):thymeleaf使用详解-thymeleaf%E4%BD%BF%E7%94%A8%E8%AF%A6%E8%A7%A3.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>

添加页面和修改类似就不在贴代码了。

效果图:

Spring Boot Jpa  Thymeleaf 增删改查示例 - 图2

这样一个使用jpa和thymeleaf的增删改查示例就完成了。