1. 程式人生 > 程式設計 >Spring boot2+jpa+thymeleaf實現增刪改查

Spring boot2+jpa+thymeleaf實現增刪改查

一、pom.xml引入相關模組web、jpa、thymeleaf、oracle:

<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>com.oracle</groupId> 
      <artifactId>ojdbc8</artifactId> 
      <version>12.2.0.1</version>     
    </dependency>

二、application.properties配置

server.port = 9001

spring.datasource.driver-class-name = oracle.jdbc.driver.OracleDriver
spring.datasource.url = jdbc:oracle:thin:@127.0.0.1:1521:testdb
spring.datasource.username = dev
spring.datasource.password = dev

spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql = true

spring.thymeleaf.cache = false

說明:

1、由於本機的8080已經被使用,修改一下埠號為9001。

2、hibernate.hbm2ddl.auto引數有四個值:

create: 每次載入hibernate時都會刪除上一次的生成的表,然後根據你的model類再重新來生成新表,哪怕兩次沒有任何改變也要
這樣執行,這就是導致資料庫表資料丟失的一個重要原因。

create-drop :每次載入hibernate時根據model類生成表,但是sessionFactory一關閉,表就自動刪除。

update:最常用的屬性,第一次載入hibernate時根據model類會自動建立起表的結構(前提是先建立好資料庫),以後載入
hibernate時根據 model類自動更新表結構,即使表結構改變了但表中的行仍然存在不會刪除以前的行。要注意的是當部署到伺服器後,表結構是不會被馬上建立起來的,是要等 應用第一次執行起來後才會。

validate :每次載入hibernate時,驗證建立資料庫表結構,只會和資料庫中的表進行比較,不會建立新表,但是會插入新值。

3、show-sql 是否打印出自動生產的SQL,方便除錯的時候檢視

4、propertiesspring.thymeleaf.cache=false是關閉thymeleaf的快取,不然在開發過程中修改頁面不會立刻生效需要重啟,生產
可配置為true。

三、啟動類需要新增Servlet的支援

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {

  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(DemoApplication.class);
  }
  
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class,args);
  }
}

四、資料庫層程式碼

1、實體類對映資料庫表

package com.example.demo.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;

import org.hibernate.validator.constraints.Length;

@Entity
@Table(name = "userinfo")
public class User {
  @Id
  @GeneratedValue
  private long id;
  
  @Column(nullable = false,unique = true)
  @NotEmpty(message="使用者名稱不能為空")
  private String userName;
  
  @Column(nullable = false)
  @NotEmpty(message="密碼不能為空")
  @Length(min=6,message="密碼長度不能少於6位")
  private String password;
  
  @Column(nullable = false)
  private int age;

  //必須有構造
   public User() {
   }
     
  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;
  }
}

2、繼承JpaRepository類會自動實現很多內建的方法

package com.example.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entity.User;

public interface UserRepository extends JpaRepository<User,Long> {
  User findById(long id);
  void deleteById(Long id);
}

五、業務層

service呼叫jpa實現相關的增刪改查,實際專案中service層處理具體的業務程式碼。

1、UserService.java

package com.example.demo.service;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.example.demo.entity.User;
public interface UserService {
  
  public Page<User> getUserPage(Pageable pageable);  
  public List<User> getUserList();
  public User findUserById(long id);
  public void save(User user);
  public void edit(User user);
  public void delete(long id);
}

2、UserServiceImpl.java

package com.example.demo.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.UserService;

@Service
public class UserServiceImpl implements UserService {
  
  @Autowired
  private UserRepository userRepository;

  @Override
  public Page<User> getUserPage(Pageable pageable) {
    return userRepository.findAll(pageable);
  }
  
  @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);
  }

}

六、控制層

package com.example.demo.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;

@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);
    
    /*int page=1,size=2;
    Sort sort = new Sort(Direction.DESC,"id");
    Pageable pageable = PageRequest.of(page,size,sort);
    model.addAttribute("users",pageable);*/
    
    return "user/list";
  }

  @RequestMapping("/toAdd")
  public String toAdd() {
    return "user/userAdd";
  }

  @RequestMapping("/add")
  public @ResponseBody User add(@Valid User user,BindingResult result) {
    if (result.hasErrors()) {
      List<ObjectError> list = result.getAllErrors();
      for (ObjectError error : list) {
        System.out.println(error.getDefaultMessage());
      }
      return null;
    }
    userService.save(user);
    return user;    
  }

  @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";
  }
}

七、頁面

1、列表頁 list.hmtl

<!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}" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></link>
</head>
<body class="container">
<br/>
<h1>使用者列表</h1>
<br/><br/>
<div class="with:80%">
  <table class="table table-hover">
    <thead>
    <tr>
      <th>#</th>
      <th>User Name</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})}" rel="external nofollow" >edit</a></td>
      <td><a th:href="@{/delete(id=${user.id})}" rel="external nofollow" >delete</a></td>
    </tr>
    </tbody>
  </table>
</div>
<div class="form-group">
  <div class="col-sm-2 control-label">
    <a href="/toAdd" rel="external nofollow" rel="external nofollow" th:href="@{/toAdd}" rel="external nofollow" class="btn btn-info">add</a>
  </div>
</div>

</body>
</html>

Spring boot2+jpa+thymeleaf實現增刪改查

2、新增頁 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}" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></link>
</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>

Spring boot2+jpa+thymeleaf實現增刪改查

3、修改頁 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}" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></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" rel="external nofollow" rel="external nofollow" th:href="@{/list}" rel="external nofollow" class="btn btn-info">Back</a>
      </div>

    </div>
  </form>
</div>
</body>
</html>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。