亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

springboot-jpa的實(shí)現(xiàn)操作

 更新時(shí)間:2021年03月02日 10:01:29   作者:斗碼士  
這篇文章主要介紹了springboot-jpa的實(shí)現(xiàn)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

JPA全稱為Java Persistence API(Java持久層API),它是Sun公司在JavaEE 5中提出的Java持久化規(guī)范。

它為Java開(kāi)發(fā)人員提供了一種對(duì)象/關(guān)聯(lián)映射工具,來(lái)管理Java應(yīng)用中的關(guān)系數(shù)據(jù),JPA吸取了目前Java持久化技術(shù)的優(yōu)點(diǎn),旨在規(guī)范、簡(jiǎn)化Java對(duì)象的持久化工作。

JPA對(duì)于單表的或者簡(jiǎn)單的SQL查詢非常友好,甚至可以說(shuō)非常智能。他為你準(zhǔn)備好了大量的拿來(lái)即用的持久層操作方法。甚至只要寫(xiě)findByName這樣一個(gè)接口方法,他就能智能的幫你執(zhí)行根據(jù)名稱查找實(shí)體類(lèi)對(duì)應(yīng)的表數(shù)據(jù),完全不用寫(xiě)SQL。

它相對(duì)于mybatis來(lái)說(shuō)不用寫(xiě)xml等配置,簡(jiǎn)直方便的不行,對(duì)于我們開(kāi)發(fā)者來(lái)說(shuō),誰(shuí)更簡(jiǎn)單,開(kāi)發(fā)效率更高,我們就喜歡誰(shuí)(不喜歡不行,看看產(chǎn)品經(jīng)理手里的菜刀)?。?!

這時(shí)候mybatis就不服了,我確實(shí)需要寫(xiě)一大堆亂七八糟的xml,但是也可以用注解啊。

還不是要寫(xiě)sql,總是一寫(xiě)增刪改查sql,有沒(méi)有把這些常見(jiàn)的增刪改查全部封裝起來(lái),我們直接調(diào)用api,sql讓它們自動(dòng)組裝就好了,說(shuō)實(shí)話我自己封裝了一個(gè)基于mybatis的組件,常見(jiàn)的增刪改查,自己組裝成sql去查詢,后來(lái)由于沒(méi)有oracle,sqlserver的數(shù)據(jù)庫(kù)環(huán)境,對(duì)這些數(shù)據(jù)庫(kù)的時(shí)間等等函數(shù)支持不好,又有jpa和mybatisplus這些現(xiàn)有的,我也就偷懶了

好了我們之前有實(shí)現(xiàn)過(guò)springboot-mybatis

springboot-mybatisplus的整合,現(xiàn)在就來(lái)實(shí)現(xiàn)一下jpa的,你們看看哪個(gè)比較方便好用,可以自己用用看

這是我實(shí)現(xiàn)的demo預(yù)覽

由于我想看到效果,又不想裝postman來(lái)測(cè)試,我就集成了swagger

最終效果如上圖

好了,我直接放代碼了

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
 
  <groupId>com.zkb</groupId>
  <artifactId>spring-data-jpa</artifactId>
  <version>1.0-SNAPSHOT</version>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>8</source>
          <target>8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <version>2.1.1.RELEASE</version>
    </dependency>
 
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
      <version>2.1.1.RELEASE</version>
    </dependency>
 
 
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.18</version>
    </dependency>
 
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.12</version>
    </dependency>
 
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <version>2.0.4.RELEASE</version>
    </dependency>
 
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <version>2.1.2.RELEASE</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.31</version>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>RELEASE</version>
      <scope>compile</scope>
    </dependency>
 
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-test</artifactId>
      <version>2.2.2.RELEASE</version>
      <scope>compile</scope>
    </dependency>
 
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.9.2</version>
      <exclusions>
        <exclusion>
          <groupId>io.swagger</groupId>
          <artifactId>swagger-annotations</artifactId>
        </exclusion>
        <exclusion>
          <groupId>io.swagger</groupId>
          <artifactId>swagger-models</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>io.swagger</groupId>
      <artifactId>swagger-annotations</artifactId>
      <version>1.5.22</version>
    </dependency>
 
    <dependency>
      <groupId>io.swagger</groupId>
      <artifactId>swagger-models</artifactId>
      <version>1.5.22</version>
    </dependency>
    <!-- swagger-ui -->
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.9.2</version>
    </dependency>
 
    <dependency>
      <groupId>com.github.xiaoymin</groupId>
      <artifactId>swagger-bootstrap-ui</artifactId>
      <version>1.9.1</version>
    </dependency>
  </dependencies>
 
</project>
server:
 port: 5001
spring:
 datasource:
  type: com.alibaba.druid.pool.DruidDataSource #Druid 是阿里巴巴開(kāi)源平臺(tái)上一個(gè)數(shù)據(jù)庫(kù)連接池實(shí)現(xiàn),結(jié)合了 C3P0、DBCP、PROXOOL 等 DB 池的優(yōu)點(diǎn),同時(shí)加入了日志監(jiān)控
  driver-class-name: com.mysql.cj.jdbc.Driver
  url: jdbc:mysql://localhost:3306/test-demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull
  username: root
  password: root
  dbcp2:
   min-idle: 5
   initial-size: 5
   max-total: 5
   max-wait-millis: 200
 jpa:
  database: mysql
  database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
  show-sql: true
  hibernate:
   ddl-auto: update
package com.zkb.entity; 
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data; 
import javax.persistence.*; 
/**
 * 實(shí)體類(lèi)
 */
@Entity
@Table(name = "t_user")
@Data
@ApiModel(value = "用戶信息", description = "用戶信息")
public class User { 
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @ApiModelProperty(value = "主鍵")
  @JsonSerialize(using = ToStringSerializer.class)
  private Long id;
 
  @Column(name = "username")
  @ApiModelProperty(value = "用戶名")
  private String username;
 
  @Column(name = "password")
  @ApiModelProperty(value = "密碼")
  private String password;
 
}
package com.zkb.dao; 
import com.zkb.entity.User;
import org.springframework.data.jpa.repository.JpaRepository; 
public interface UserRepository extends JpaRepository<User,Long> {
}
package com.zkb.service; 
import com.zkb.entity.User; 
import java.util.List; 
public interface UserService { 
  public void deleteUser(Long id); 
  List<User> getList();
}
package com.zkb.service.impl; 
import com.zkb.dao.UserRepository;
import com.zkb.entity.User;
import com.zkb.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 void deleteUser(Long id) {
    System.out.println(userRepository);
    userRepository.deleteById(id);
  }
 
  @Override
  public List<User> getList() {
    return userRepository.findAll();
  }
}
package com.zkb.controller; 
import com.zkb.entity.User;
import com.zkb.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; 
import java.util.List; 
@RestController
@RequestMapping("/user")
@Api(value = "user",tags = "user")
public class UserController {
 
  @Autowired
  private UserService userService;
 
  @PostMapping("/del")
  @ApiOperation(value="刪除",notes = "刪除")
  public String delete(@RequestParam("id") Long id){
    userService.deleteUser(id);
    return "true";
  }
 
  @PostMapping("/getList")
  @ApiOperation(value="查詢所有",notes = "查詢所有")
  public List<User> getList(){
    return userService.getList();
  }
}
package com.zkb.conf; 
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; 
import java.util.Arrays;
import java.util.List; 
@Configuration
@EnableSwagger2
public class SwaggerApp {  
  @Bean
  public Docket createRestApi1() {
    return new Docket(DocumentationType.SWAGGER_2).enable(true).apiInfo(apiInfo()).select()
        .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
        .apis(RequestHandlerSelectors.basePackage("com.zkb.controller"))
        .paths(PathSelectors.any()).build().securitySchemes(apiKeyList()).groupName("接口中心");
  }
 
  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title("API")
        .contact(new Contact("XXXXX", "http://XXXXXX.XXXX/", ""))
        .version("1.0")
        .description("API 描述")
        .build();
  }
 
  private List<ApiKey> apiKeyList() {
    return Arrays.asList(new ApiKey("登錄token", "token", In.HEADER.name()),
        new ApiKey("設(shè)備類(lèi)型(android,ios,pc)---必填", "deviceType", In.HEADER.name()));
  }
}
package com.zkb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class App {
  public static void main(String[] args) {
    SpringApplication.run(App.class,args);
  }
}
CREATE TABLE `t_user` (
 `id` bigint NOT NULL AUTO_INCREMENT,
 `username` varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL,
 `password` varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL,
 PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1214893367637352451 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

非常簡(jiǎn)單的一張表,注意數(shù)據(jù)庫(kù)名稱

到這里就已經(jīng)實(shí)現(xiàn)了一個(gè)非常簡(jiǎn)單的jpa demo了

當(dāng)然我這里只是指路,讓知怎么用

補(bǔ)充:SpringBoot使用JPA實(shí)現(xiàn)增刪查改

一、運(yùn)行環(huán)境

SpringBoot2.3.0

JDK1.8

IDEA2020.1.2

MySQL5.7

二、依賴及應(yīng)用程序配置

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</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-validation</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <optional>true</optional>
</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>

1、升級(jí)到SpringBoot2.2,spring-boot-starter-test默認(rèn)使用JUnit 5作為單元測(cè)試框架 ,寫(xiě)單元測(cè)試時(shí)注解@RunWith(Spring.class)升級(jí)為@ExtendWith(SpringExtension.class)

2、升級(jí)到SpringBoot2.3,hibernate-validator從spring-boot-starter-web移除,需要單獨(dú)引入

3、升級(jí)到SpringBoot2.3,MySQL驅(qū)動(dòng)由com.mysql.jdbc.Driver變更為com.mysql.cj.jdbc.Driver;同時(shí),數(shù)據(jù)源url需要添加serverTimezone=UTC&useSSL=false參數(shù)

3、升級(jí)到SpringBoot2.x,默認(rèn)不自動(dòng)注入HiddenHttpMethodFilter,需要設(shè)置spring.mvc.hiddenmethod.filter.enabled=true開(kāi)啟PUT、DELETE方法支持

應(yīng)用程序配置如下:

spring.application.name=springbootjpa
management.endpoints.jmx.exposure.include=*
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
# 應(yīng)用服務(wù) WEB 訪問(wèn)端口
server.port=8080
# Actuator Web 訪問(wèn)端口
management.server.port=8081
# mysql setting
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springbootjpa?serverTimezone=UTC&useSSL=false
spring.datasource.username=username
spring.datasource.password=password
# JPA setting
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
# thymeleaf setting
spring.thymeleaf.cache=false
# delete、put方法支持
spring.mvc.hiddenmethod.filter.enabled=true

三、定義實(shí)體

使用@Entity標(biāo)記實(shí)體類(lèi)

import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
@Entity
@Data
public class Article extends BaseEntity implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  @Column(nullable = false, unique = true)
  @NotEmpty(message = "標(biāo)題不能為空")
  private String title;
  @Column(nullable = false)
  private String body;
}

為了自動(dòng)添加創(chuàng)建日期、修改日期、創(chuàng)建人及修改人,我們把創(chuàng)建、修改信息放到父類(lèi)中由實(shí)體類(lèi)繼承,并開(kāi)啟SpringBoot的自動(dòng)審計(jì)功能,將創(chuàng)建/修改信息自動(dòng)注入

1、定義實(shí)體類(lèi)的父類(lèi),@CreatedDate、@LastModifiedDate、@CreatedBy、@LastModifiedBy標(biāo)注相應(yīng)字段

import org.hibernate.annotations.Columns;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseEntity {
  @CreatedDate
  private Long createTime;
  @LastModifiedDate
  private Long updateTime;
  
  @Column(name = "create_by")
  @CreatedBy
  private String createBy;
  @Column(name = "lastmodified_by")
  @LastModifiedBy
  private String lastmodifiedBy;
  
  public Long getCreateTime() {
    return createTime;
  }
  public void setCreateTime(Long createTime) {
    this.createTime = createTime;
  }
  public Long getUpdateTime() {
    return updateTime;
  }
  public void setUpdateTime(Long updateTime) {
    this.updateTime = updateTime;
  }
  
  public String getCreateBy() {
    return createBy;
  }
  public void setCreateBy(String createBy) {
    this.createBy = createBy;
  }
  public String getLastmodifiedBy() {
    return lastmodifiedBy;
  }
  public void setLastmodifiedBy(String lastmodifiedBy) {
    this.lastmodifiedBy = lastmodifiedBy;
  }
}

@MappedSuperclass注解:

作用于實(shí)體類(lèi)的父類(lèi)上,父類(lèi)不生成對(duì)應(yīng)的數(shù)據(jù)庫(kù)表

標(biāo)注@MappedSuperclass的類(lèi)不能再標(biāo)注@Entity或@Table注解,也無(wú)需實(shí)現(xiàn)序列化接口

每個(gè)子類(lèi)(實(shí)體類(lèi))對(duì)應(yīng)一張數(shù)據(jù)庫(kù)表,數(shù)據(jù)庫(kù)表包含子類(lèi)屬性和父類(lèi)屬性

標(biāo)注@MappedSuperclass的類(lèi)可以直接標(biāo)注@EntityListeners實(shí)體監(jiān)聽(tīng)器

@EntityListeners(AuditingEntityListener.class)注解:

作用范圍僅在標(biāo)注@MappedSuperclass類(lèi)的所有繼承類(lèi)中,并且實(shí)體監(jiān)聽(tīng)器可以被其子類(lèi)繼承或重載

開(kāi)啟JPA的審計(jì)功能,需要在SpringBoot的入口類(lèi)標(biāo)注@EnableJpaAuditing

創(chuàng)建日期、修改日期有默認(rèn)方法注入值,但創(chuàng)建人和修改人注入則需要手動(dòng)實(shí)現(xiàn)AuditorAware接口:

@Configuration
public class BaseEntityAuditor implements AuditorAware<String> {
  @Override
  public Optional<String> getCurrentAuditor() {
    return "";
  }
}

四、DAO層實(shí)現(xiàn)

JPA支持通過(guò)約定方法名進(jìn)行數(shù)據(jù)庫(kù)查詢、修改:

import org.springframework.data.jpa.repository.JpaRepository;
import springbootjpa.entity.Article;
public interface ArticleRepository extends JpaRepository<Article, Long> {
  Article findById(long id);
}

通過(guò)約定方法名查詢,只需實(shí)現(xiàn)JpaRepository接口聲明查詢方法而不需要具體實(shí)現(xiàn)

此外,可以在方法上標(biāo)注@Query實(shí)現(xiàn)JPQL或原生SQL查詢

JpaRepository<T, ID>,T表示要操作的實(shí)體對(duì)象,ID表示主鍵。該接口繼承了分頁(yè)排序接口PadingAndSortRepository,通過(guò)構(gòu)建Pageable實(shí)現(xiàn)分頁(yè)查詢:

@Autowired
private ArticleRepository articleRepository;
@RequestMapping("")
public ModelAndView articlelist(@RequestParam(value = "start", defaultValue = "0") Integer start, @RequestParam(value = "limit", defaultValue = "5") Integer limit) {
    start = start < 0 ? 0 : start;
    Sort sort = Sort.by(Sort.Direction.DESC, "id");
    Pageable pageable = PageRequest.of(start, limit, sort);
    Page<Article> page = articleRepository.findAll(pageable);
    ModelAndView modelAndView = new ModelAndView("article/list");
    modelAndView.addObject("page", page);
    return modelAndView;
}

如果根據(jù)某一字段排序,可以用Sort.by方法構(gòu)建Sort對(duì)象;如果根據(jù)多個(gè)字段排序,首先構(gòu)建Sort.Order數(shù)組List<Sort.Order>,然后再傳入Sort.by方法構(gòu)建Sort對(duì)象。

PageRequest.of方法生成Pageable對(duì)象

五、Contrller 控制器

import org.springframework.beans.factory.annotation.Autowired;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import springbootjpa.entity.Article;
import springbootjpa.repository.ArticleRepository;
@Controller
@RequestMapping("/article")
public class ArticleController {
  @Autowired
  private ArticleRepository articleRepository;
  @RequestMapping("")
  public ModelAndView articlelist(@RequestParam(value = "start", defaultValue = "0") Integer start,
                  @RequestParam(value = "limit", defaultValue = "5") Integer limit) {
    start = start < 0 ? 0 : start;
    Sort sort = Sort.by(Sort.Direction.DESC, "id");
    Pageable pageable = PageRequest.of(start, limit, sort);
    Page<Article> page = articleRepository.findAll(pageable);
    ModelAndView modelAndView = new ModelAndView("article/list");
    modelAndView.addObject("page", page);
    return modelAndView;
  }
  @RequestMapping("/add")
  public String addArticle() {
    return "article/add";
  }
  @PostMapping("")
  public String saveArticle(Article article) {
    articleRepository.save(article);
    return "redirect:/article";
  }
  @GetMapping("/{id}")
  public ModelAndView getArticle(@PathVariable("id") Integer id) {
    Article article = articleRepository.findById(id);
    ModelAndView modelAndView = new ModelAndView("article/show");
    modelAndView.addObject("article", article);
    return modelAndView;
  }
  @DeleteMapping("/{id}")
  public String deleteArticle(@PathVariable("id") long id) {
    System.out.println("put 方法");
    articleRepository.deleteById(id);
    return "redirect:/article";
  }
  @GetMapping("edit/{id}")
  public ModelAndView editArticle(@PathVariable("id") Integer id) {
    Article article = articleRepository.findById(id);
    ModelAndView modelAndView = new ModelAndView("article/edit");
    modelAndView.addObject("article", article);
    return modelAndView;
  }
  @PutMapping("/{id}")
  public String editArticleSave(Article article, long id) {
    System.out.println("put 方法");
    article.setId(id);
    articleRepository.save(article);
    return "redirect:/article";
  }
}

因?yàn)?lt;form>表單只能發(fā)送GET或POST請(qǐng)求,spring3引入一個(gè)監(jiān)聽(tīng)器HiddenHttpMethodFilter來(lái)將POST請(qǐng)求轉(zhuǎn)換為PUT或POST請(qǐng)求。

SpringBoot2.x開(kāi)始默認(rèn)不自動(dòng)注入HiddenHttpMethodFilter,需要設(shè)置spring.mvc.hiddenmethod.filter.enabled=true開(kāi)啟PUT、DELETE方法支持

配置完后,前端頁(yè)面需要在表單中加入隱藏域,表明實(shí)際請(qǐng)求方法:

<!-- DELETE 請(qǐng)求 -->
<form id="deletePost" method="POST" action="">
<input type="hidden" name="_method" value="delete">
</form>
<!-- PUT 請(qǐng)求 -->
<form id="putPost" method="POST" action="">
<input type="hidden" name="_method" value="put">
</form>

六、其他

th:value和th:field區(qū)別:

th:value解析成html,表現(xiàn)為:value="${th:value}"

th:field解析成html,表現(xiàn)為:name="${th:name}" value="${th:value}"

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

  • Spring?Security如何為用戶示例添加角色詳解

    Spring?Security如何為用戶示例添加角色詳解

    目前我正在用Java開(kāi)發(fā)一個(gè)基于Spring Boot的web應(yīng)用程序,下面這篇文章主要給大家介紹了關(guān)于Spring?Security如何為用戶示例添加角色的相關(guān)資料,需要的朋友可以參考下
    2022-10-10
  • mybatis主從表關(guān)聯(lián)查詢,返回對(duì)象帶有集合屬性解析

    mybatis主從表關(guān)聯(lián)查詢,返回對(duì)象帶有集合屬性解析

    這篇文章主要介紹了mybatis主從表關(guān)聯(lián)查詢,返回對(duì)象帶有集合屬性解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • MyBatis嵌套查詢collection報(bào)錯(cuò):org.apache.ibatis.exceptions.TooManyResultsException

    MyBatis嵌套查詢collection報(bào)錯(cuò):org.apache.ibatis.exceptions.TooMany

    本文主要介紹了MyBatis嵌套查詢collection報(bào)錯(cuò):org.apache.ibatis.exceptions.TooManyResultsException,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2024-09-09
  • Java實(shí)現(xiàn)學(xué)生管理系統(tǒng)詳解流程

    Java實(shí)現(xiàn)學(xué)生管理系統(tǒng)詳解流程

    這篇文章主要為大家詳細(xì)介紹了如何利用Java語(yǔ)言實(shí)現(xiàn)學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-06-06
  • springboot手動(dòng)動(dòng)態(tài)注入controller和service方式

    springboot手動(dòng)動(dòng)態(tài)注入controller和service方式

    這篇文章主要介紹了springboot手動(dòng)動(dòng)態(tài)注入controller和service方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • JAVA 格式化日期、時(shí)間的方法

    JAVA 格式化日期、時(shí)間的方法

    這篇文章主要介紹了JAVA 格式化日期、時(shí)間的方法,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-06-06
  • SpringBoot實(shí)現(xiàn)PDF轉(zhuǎn)圖片的代碼示例

    SpringBoot實(shí)現(xiàn)PDF轉(zhuǎn)圖片的代碼示例

    在本文中,我們使用SpringBoot演示了如何將PDF文件轉(zhuǎn)換為一張或多張圖片,這些示例演示了如何使用Java編程語(yǔ)言與其他開(kāi)源技術(shù)集成,以實(shí)現(xiàn)各種文件格式之間的轉(zhuǎn)換,感興趣的小伙伴跟著小編一起來(lái)看看吧
    2024-08-08
  • 詳解用maven將dubbo工程打成jar包運(yùn)行

    詳解用maven將dubbo工程打成jar包運(yùn)行

    這篇文章主要介紹了詳解用maven將dubbo工程打成jar包運(yùn)行,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • 使用java模擬簡(jiǎn)單的tomcat的方法詳解

    使用java模擬簡(jiǎn)單的tomcat的方法詳解

    這篇文章主要為大家詳細(xì)介紹了java模擬簡(jiǎn)單的tomcat的方法,使用數(shù)據(jù)庫(kù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • Struts2 漏洞分析及如何提前預(yù)防

    Struts2 漏洞分析及如何提前預(yù)防

    2016年4月26日,Struts2發(fā)布一份安全公告,CVE編號(hào) CVE-2016-3081。這是自2012年Struts2命令執(zhí)行漏洞大規(guī)模爆發(fā)之后,該服務(wù)時(shí)隔四年再次爆發(fā)大規(guī)模漏洞。該漏洞也是今年目前爆出的最嚴(yán)重安全漏洞。本文分析了漏洞的原理危害影響防護(hù)等內(nèi)容。
    2016-05-05

最新評(píng)論