Spring Boot Crud操作示例 | Java Code Geeks
,在本教程中,我們將探討spring框架的spring boot模組中的crud操作。
簡介
- Spring Boot是一個為spring框架提供快速應用程式開發功能的模組,包括自動配置,獨立程式碼和生產就緒程式碼
- 它建立打包為jar的應用程式,並使用嵌入式servlet容器(例如Tomcat,Jetty或Undertow)直接啟動。因此,無需部署war檔案
- 它透過提供入門模板簡化了maven配置,並有助於解決依賴衝突。它會自動識別所需的依賴項並在應用程式中匯入它們
- 它有助於刪除樣板程式碼,額外註釋和xml配置
- 它提供強大的批處理並管理其餘端點
- 它提供了一個高效的jpa-starter庫,可以有效地將應用程式與關聯式資料庫連線起來
現在,讓我們看看如何在spring boot模組中使用jpa-starter庫與關聯式資料庫進行通訊來實現本教程。
建立Spring Boot應用程式
以下是開發應用程式所涉及的Maven依賴
在這裡,我們指定Spring Boot,Spring Boot JPA和MySQL聯結器的依賴項。Maven將自動解析其他依賴項。該更新檔案將具有下面的程式碼。步驟。
<!-- Spring boot web mvc jar --> <!-- Automatically adds tomcat and jackson-databind jars --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring boot jpa jar --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- Mysql database jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> |
在Springbootcrudoperation/src/main/resources/建立一個新的屬性檔案application.properties:並向其中新增以下程式碼。
## Spring datasource. spring.datasource.driver.class=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/paramount spring.datasource.username=root spring.datasource.password= ## Hibernate properties. spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect ## Show sql query. spring.jpa.show-sql=true ## Hibernate ddl auto. spring.jpa.hibernate.ddl-auto=validate |
將以下程式碼新增到主類中以從main方法引導應用程式。永遠記住,spring boot應用程式的入口點是包含@SpringBootApplication註釋和靜態main方法的類。
package com.ducat.springboot.rest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Myapplication { public static void main(String[] args) { SpringApplication.run(Myapplication.class, args); } } |
將以下程式碼新增到員工模型類。
Employee.java:
package com.ducat.springboot.rest.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import org.springframework.stereotype.Component; @Component // Spring jpa jars. @Entity @Table(name= "employee") // To increase speed and save sql statement execution time. @DynamicInsert @DynamicUpdate public class Employee { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private int id; private String name; private String department; private double salary; public Employee() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", department=" + department + ", salary=" + salary + "]"; } } |
將以下程式碼新增到擴充套件JPA儲存庫的Dao介面,以自動處理crud查詢。
Mydaorepository.java
package com.ducat.springboot.rest.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.ducat.springboot.rest.model.Employee; @Repository public interface Mydaorepository extends JpaRepository<Employee, Integer> { } |
將以下程式碼新增到服務類中,我們將呼叫Dao介面的方法來處理sql操作。
@Service public class Myserviceimpl implements Myservice { @Autowired Mydaorepository dao; @Override public List<Employee> getEmployees() { return dao.findAll(); } @Override public Optional<Employee> getEmployeeById(int empid) { return dao.findById(empid); } @Override public Employee addNewEmployee(Employee emp) { return dao.save(emp); } @Override public Employee updateEmployee(Employee emp) { return dao.save(emp); } @Override public void deleteEmployeeById(int empid) { dao.deleteById(empid); } @Override public void deleteAllEmployees() { dao.deleteAll(); } } |
將以下程式碼新增到旨在處理傳入請求的控制器類中。該類使用註釋進行@RestController註釋,其中每個方法都將域物件作為json響應而不是檢視返回。
package com.ducat.springboot.rest.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.ducat.springboot.rest.model.Employee; import com.ducat.springboot.rest.service.Myservice; @RestController public class Mycontroller { @Autowired Myservice service; @RequestMapping(value= "/employee/all", method= RequestMethod.GET) public List<Employee> getEmployees() { System.out.println(this.getClass().getSimpleName() + " - Get all employees service is invoked."); return service.getEmployees(); } @RequestMapping(value= "/employee/{id}", method= RequestMethod.GET) public Employee getEmployeeById(@PathVariable int id) throws Exception { System.out.println(this.getClass().getSimpleName() + " - Get employee details by id is invoked."); Optional<Employee> emp = service.getEmployeeById(id); if(!emp.isPresent()) throw new Exception("Could not find employee with id- " + id); return emp.get(); } @RequestMapping(value= "/employee/add", method= RequestMethod.POST) public Employee createEmployee(@RequestBody Employee newemp) { System.out.println(this.getClass().getSimpleName() + " - Create new employee method is invoked."); return service.addNewEmployee(newemp); } @RequestMapping(value= "/employee/update/{id}", method= RequestMethod.PUT) public Employee updateEmployee(@RequestBody Employee updemp, @PathVariable int id) throws Exception { System.out.println(this.getClass().getSimpleName() + " - Update employee details by id is invoked."); Optional<Employee> emp = service.getEmployeeById(id); if (!emp.isPresent()) throw new Exception("Could not find employee with id- " + id); /* IMPORTANT - To prevent the overriding of the existing value of the variables in the database, * if that variable is not coming in the @RequestBody annotation object. */ if(updemp.getName() == null || updemp.getName().isEmpty()) updemp.setName(emp.get().getName()); if(updemp.getDepartment() == null || updemp.getDepartment().isEmpty()) updemp.setDepartment(emp.get().getDepartment()); if(updemp.getSalary() == 0) updemp.setSalary(emp.get().getSalary()); // Required for the "where" clause in the sql query template. updemp.setId(id); return service.updateEmployee(updemp); } @RequestMapping(value= "/employee/delete/{id}", method= RequestMethod.DELETE) public void deleteEmployeeById(@PathVariable int id) throws Exception { System.out.println(this.getClass().getSimpleName() + " - Delete employee by id is invoked."); Optional<Employee> emp = service.getEmployeeById(id); if(!emp.isPresent()) throw new Exception("Could not find employee with id- " + id); service.deleteEmployeeById(id); } @RequestMapping(value= "/employee/deleteall", method= RequestMethod.DELETE) public void deleteAll() { System.out.println(this.getClass().getSimpleName() + " - Delete all employees is invoked."); service.deleteAllEmployees(); } } |
執行應用程式
當我們準備好所有更改時,讓我們編譯spring boot專案並將應用程式作為java專案執行。
使用Postman測試:
// Get all employees http://localhost:8080/employee/all // Get employee by id http://localhost:8080/employee/1003 // Create new employee http://localhost:8080/employee/add // Update existing employee by id http://localhost:8080/employee/update/1008 // Delete employee by id http://localhost:8080/employee/delete/1002 // Delete all employees http://localhost:8080/employee/deleteall |
這就是本教程的全部內容,我希望這篇文章能為您提供所需的一切。快樂學習,別忘了分享!
重點
- 我們指示hibernate連線到mysql資料庫並使用它MySQL5Dialect來生成最佳化的sql查詢
- spring.jpa.hibernate.ddl-auto=validate 將指示hibernate在應用程式啟動時驗證表模式
- spring.jpa.show-sql=true 將指示hibernate框架記錄控制檯上的所有SQL語句
- 開發人員可以根據需要更改資料來源詳細資訊
相關文章
- Spring Boot+MiniUI CRUD操作Spring BootUI
- Spring Boot整合Mybatis完成級聯一對多CRUD操作Spring BootMyBatis
- Java Hibernate 之 CRUD 操作Java
- spring 整合 mybatis 及mybatis 的 crud 操作SpringMyBatis
- Spring Boot (十五): Spring Boot + Jpa + Thymeleaf 增刪改查示例Spring Boot
- 使用Spring Boot反應式R2DBC實現PostgreSQL的CRUD操作原始碼 - RajeshSpring BootSQL原始碼
- Spring Boot的基本操作Spring Boot
- 淺出Spring Boot系列(二)程式碼組織及CRUDSpring Boot
- 使用Spring Boot實現的GraphQL示例Spring Boot
- Spring Boot中快速操作MongodbSpring BootMongoDB
- Java 8 Streams 中的資料庫 CRUD 操作Java資料庫
- Elasticsearch CRUD基本操作Elasticsearch
- go操作mongo CRUDGo
- Spring Boot 2.5.x能支援Java 17了 - codecentricSpring BootJava
- Java Web之Spring BootJavaWebSpring Boot
- Spring Boot整合Redis實戰操作Spring BootRedis
- testng + mockito + spring boot test 基本操作MockitoSpring Boot
- Spring Boot (五)Spring Data JPA 操作 MySQL 8Spring BootMySql
- Spring boot學習(六)Spring boot實現AOP記錄操作日誌Spring Boot
- Spring Boot MongoDB 查詢操作 (BasicQuery ,BSON)Spring BootMongoDB
- Spring Boot(六)整合 MyBatis 操作 MySQL 8Spring BootMyBatisMySql
- Spring Boot 中使用 Jedis 來操作 RedisSpring BootRedis
- Spring BOOT 整合 RabbitMq 實戰操作(一)Spring BootMQ
- Spring Boot實戰:資料庫操作Spring Boot資料庫
- 在Spring Boot快取API - Code FactorySpring Boot快取API
- Java之Spring Boot詳解JavaSpring Boot
- 利用spring boot建立java appSpring BootJavaAPP
- MyBatis 的簡單 CRUD 操作MyBatis
- Mybatis:CRUD操作及配置解析MyBatis
- 使用PreparedStatement實現CRUD操作
- spring boot請求字尾匹配的操作Spring Boot
- Spring Boot 整合 Redis 實現快取操作Spring BootRedis快取
- spring boot 日誌介紹 以及 logback配置示例Spring Boot
- Spring Boot與Kafka + kafdrop結合使用的簡單示例Spring BootKafka
- Java Web系列:Spring Boot 基礎JavaWebSpring Boot
- spring boot kotlin java 混編Spring BootKotlinJava
- 8、使用 Spring Boot 搭建的一個 Spring MVC 示例(持續更新中)Spring BootMVC
- Spring Boot整合Spring Data JPA進行資料庫操作Spring Boot資料庫