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
- 在Spring Boot快取API - Code FactorySpring Boot快取API
- Spring Boot的基本操作Spring Boot
- 使用Spring Boot反應式R2DBC實現PostgreSQL的CRUD操作原始碼 - RajeshSpring BootSQL原始碼
- 使用Spring Boot實現的GraphQL示例Spring Boot
- Spring Boot中快速操作MongodbSpring BootMongoDB
- spring boot學習(5): 程式exit code自定義Spring Boot
- Spring Boot (五)Spring Data JPA 操作 MySQL 8Spring BootMySql
- testng + mockito + spring boot test 基本操作MockitoSpring Boot
- Spring Boot整合Redis實戰操作Spring BootRedis
- go操作mongo CRUDGo
- Elasticsearch CRUD基本操作Elasticsearch
- Spring boot學習(六)Spring boot實現AOP記錄操作日誌Spring Boot
- Spring Boot MongoDB 查詢操作 (BasicQuery ,BSON)Spring BootMongoDB
- Spring Boot(六)整合 MyBatis 操作 MySQL 8Spring BootMyBatisMySql
- spring boot kotlin java 混編Spring BootKotlinJava
- Java之Spring Boot詳解JavaSpring Boot
- Laravel-Gii Visual code generation tool CRUD + GUILaravelGUI
- Spring Boot整合Spring Data JPA進行資料庫操作Spring Boot資料庫
- Spring Boot整合Spring Cloud Task實現批處理操作Spring BootCloud
- spring boot請求字尾匹配的操作Spring Boot
- Spring Data MongoDB 操作 document DB 的詳細示例SpringMongoDB
- spring boot 2.0 整合 oauth2 authorization code授權碼模式Spring BootOAuth模式
- Spring Boot與Kafka + kafdrop結合使用的簡單示例Spring BootKafka
- MyBatis 的簡單 CRUD 操作MyBatis
- Mybatis:CRUD操作及配置解析MyBatis
- 使用PreparedStatement實現CRUD操作
- Spring-Boot-操作-Redis,三種方案全解析!SpringbootRedis
- Spring boot方式使用MyBatis-Plus分頁操作Spring BootMyBatis
- Spring Boot:Spring Boot配置SwaggerSpring BootSwagger
- Spring Boot:Spring Boot配置MybatisSpring BootMyBatis
- java工程管理系統原始碼+spring cloud + spring bootJava原始碼CloudSpring Boot
- Java CRaC 上的Spring Boot3JavaSpring Boot
- Java Spring Boot 學習筆記(一)JavaSpring Boot筆記
- spring boot基於Java的容器配置Spring BootJava
- 開始使用GraphQL Java和Spring BootJavaSpring Boot
- 07-SpringBoot+MyBatis+Spring 技術整合實現商品模組的CRUD操作Spring BootMyBatis