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.<b>class</b>=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql:<font><i>//localhost:3306/paramount</i></font><font> 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=<b>true</b> ## Hibernate ddl auto. spring.jpa.hibernate.ddl-auto=validate </font>
將以下程式碼新增到主類中以從main方法引導應用程式。永遠記住,spring boot應用程式的入口點是包含@SpringBootApplication註釋和靜態main方法的類。
<b>package</b> com.ducat.springboot.<b>rest</b>; <b>import</b> org.springframework.boot.SpringApplication; <b>import</b> org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication <b>public</b> <b>class</b> Myapplication { <b>public</b> <b>static</b> <b>void</b> main(String[] args) { SpringApplication.run(Myapplication.<b>class</b>, args); } }
將以下程式碼新增到員工模型類。
Employee.java:
<b>package</b> com.ducat.springboot.<b>rest</b>.model; <b>import</b> javax.persistence.Entity; <b>import</b> javax.persistence.GeneratedValue; <b>import</b> javax.persistence.GenerationType; <b>import</b> javax.persistence.Id; <b>import</b> javax.persistence.Table; <b>import</b> org.hibernate.annotations.DynamicInsert; <b>import</b> org.hibernate.annotations.DynamicUpdate; <b>import</b> org.springframework.stereotype.Component; @Component <font><i>// Spring jpa jars.</i></font><font> @Entity @Table(name= </font><font>"employee"</font><font>) </font><font><i>// To increase speed and save sql statement execution time.</i></font><font> @DynamicInsert @DynamicUpdate <b>public</b> <b>class</b> Employee { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) <b>private</b> <b>int</b> id; <b>private</b> String name; <b>private</b> String department; <b>private</b> <b>double</b> salary; <b>public</b> Employee() { } <b>public</b> <b>int</b> getId() { <b>return</b> id; } <b>public</b> <b>void</b> setId(<b>int</b> id) { <b>this</b>.id = id; } <b>public</b> String getName() { <b>return</b> name; } <b>public</b> <b>void</b> setName(String name) { <b>this</b>.name = name; } <b>public</b> String getDepartment() { <b>return</b> department; } <b>public</b> <b>void</b> setDepartment(String department) { <b>this</b>.department = department; } <b>public</b> <b>double</b> getSalary() { <b>return</b> salary; } <b>public</b> <b>void</b> setSalary(<b>double</b> salary) { <b>this</b>.salary = salary; } @Override <b>public</b> String toString() { <b>return</b> </font><font>"Employee [id="</font><font> + id + </font><font>", name="</font><font> + name + </font><font>", department="</font><font> + department + </font><font>", salary="</font><font> + salary + </font><font>"]"</font><font>; } } </font>
將以下程式碼新增到擴充套件JPA儲存庫的Dao介面,以自動處理crud查詢。
Mydaorepository.java
<b>package</b> com.ducat.springboot.<b>rest</b>.dao; <b>import</b> org.springframework.data.jpa.repository.JpaRepository; <b>import</b> org.springframework.stereotype.Repository; <b>import</b> com.ducat.springboot.<b>rest</b>.model.Employee; @Repository <b>public</b> <b>interface</b> Mydaorepository <b>extends</b> JpaRepository<Employee, Integer> { }
將以下程式碼新增到服務類中,我們將呼叫Dao介面的方法來處理sql操作。
@Service <b>public</b> <b>class</b> Myserviceimpl implements Myservice { @Autowired Mydaorepository dao; @Override <b>public</b> List<Employee> getEmployees() { <b>return</b> dao.findAll(); } @Override <b>public</b> Optional<Employee> getEmployeeById(<b>int</b> empid) { <b>return</b> dao.findById(empid); } @Override <b>public</b> Employee addNewEmployee(Employee emp) { <b>return</b> dao.save(emp); } @Override <b>public</b> Employee updateEmployee(Employee emp) { <b>return</b> dao.save(emp); } @Override <b>public</b> <b>void</b> deleteEmployeeById(<b>int</b> empid) { dao.deleteById(empid); } @Override <b>public</b> <b>void</b> deleteAllEmployees() { dao.deleteAll(); } }
將以下程式碼新增到旨在處理傳入請求的控制器類中。該類使用註釋進行@RestController註釋,其中每個方法都將域物件作為json響應而不是檢視返回。
<b>package</b> com.ducat.springboot.<b>rest</b>.controller; <b>import</b> java.util.List; <b>import</b> java.util.Optional; <b>import</b> org.springframework.beans.factory.annotation.Autowired; <b>import</b> org.springframework.web.bind.annotation.PathVariable; <b>import</b> org.springframework.web.bind.annotation.RequestBody; <b>import</b> org.springframework.web.bind.annotation.RequestMapping; <b>import</b> org.springframework.web.bind.annotation.RequestMethod; <b>import</b> org.springframework.web.bind.annotation.RestController; <b>import</b> com.ducat.springboot.<b>rest</b>.model.Employee; <b>import</b> com.ducat.springboot.<b>rest</b>.service.Myservice; @RestController <b>public</b> <b>class</b> Mycontroller { @Autowired Myservice service; @RequestMapping(value= <font>"/employee/all"</font><font>, method= RequestMethod.GET) <b>public</b> List<Employee> getEmployees() { System.out.println(<b>this</b>.getClass().getSimpleName() + </font><font>" - Get all employees service is invoked."</font><font>); <b>return</b> service.getEmployees(); } @RequestMapping(value= </font><font>"/employee/{id}"</font><font>, method= RequestMethod.GET) <b>public</b> Employee getEmployeeById(@PathVariable <b>int</b> id) throws Exception { System.out.println(<b>this</b>.getClass().getSimpleName() + </font><font>" - Get employee details by id is invoked."</font><font>); Optional<Employee> emp =service.getEmployeeById(id); <b>if</b>(!emp.isPresent()) <b>throw</b> <b>new</b> Exception(</font><font>"Could not find employee with id- "</font><font> + id); <b>return</b> emp.get(); } @RequestMapping(value= </font><font>"/employee/add"</font><font>, method= RequestMethod.POST) <b>public</b> Employee createEmployee(@RequestBody Employee newemp) { System.out.println(<b>this</b>.getClass().getSimpleName() + </font><font>" - Create new employee method is invoked."</font><font>); <b>return</b> service.addNewEmployee(newemp); } @RequestMapping(value= </font><font>"/employee/update/{id}"</font><font>, method= RequestMethod.PUT) <b>public</b> Employee updateEmployee(@RequestBody Employee updemp, @PathVariable <b>int</b> id) throws Exception { System.out.println(<b>this</b>.getClass().getSimpleName() + </font><font>" - Update employee details by id is invoked."</font><font>); Optional<Employee> emp =service.getEmployeeById(id); <b>if</b> (!emp.isPresent()) <b>throw</b> <b>new</b> Exception(</font><font>"Could not find employee with id- "</font><font> + id); </font><font><i>/* 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. */</i></font><font> <b>if</b>(updemp.getName() == <b>null</b> || updemp.getName().isEmpty()) updemp.setName(emp.get().getName()); <b>if</b>(updemp.getDepartment() == <b>null</b> || updemp.getDepartment().isEmpty()) updemp.setDepartment(emp.get().getDepartment()); <b>if</b>(updemp.getSalary() == 0) updemp.setSalary(emp.get().getSalary()); </font><font><i>// Required for the "where" clause in the sql query template.</i></font><font> updemp.setId(id); <b>return</b> service.updateEmployee(updemp); } @RequestMapping(value= </font><font>"/employee/delete/{id}"</font><font>, method= RequestMethod.DELETE) <b>public</b> <b>void</b> deleteEmployeeById(@PathVariable <b>int</b> id) throws Exception { System.out.println(<b>this</b>.getClass().getSimpleName() + </font><font>" - Delete employee by id is invoked."</font><font>); Optional<Employee> emp =service.getEmployeeById(id); <b>if</b>(!emp.isPresent()) <b>throw</b> <b>new</b> Exception(</font><font>"Could not find employee with id- "</font><font> + id); service.deleteEmployeeById(id); } @RequestMapping(value= </font><font>"/employee/deleteall"</font><font>, method= RequestMethod.DELETE) <b>public</b> <b>void</b> deleteAll() { System.out.println(<b>this</b>.getClass().getSimpleName() + </font><font>" - Delete all employees is invoked."</font><font>); service.deleteAllEmployees(); } } </font>
執行應用程式
當我們準備好所有更改時,讓我們編譯spring boot專案並將應用程式作為java專案執行。
使用Postman測試:
<font><i>// Get all employees</i></font><font> http:</font><font><i>//localhost:8080/employee/all</i></font><font> </font><font><i>// Get employee by id</i></font><font> http:</font><font><i>//localhost:8080/employee/1003</i></font><font> </font><font><i>// Create new employee</i></font><font> http:</font><font><i>//localhost:8080/employee/add</i></font><font> </font><font><i>// Update existing employee by id</i></font><font> http:</font><font><i>//localhost:8080/employee/update/1008</i></font><font> </font><font><i>// Delete employee by id</i></font><font> http:</font><font><i>//localhost:8080/employee/delete/1002</i></font><font> </font><font><i>// Delete all employees</i></font><font> http:</font><font><i>//localhost:8080/employee/deleteall</i></font><font> </font>
這就是本教程的全部內容,我希望這篇文章能為您提供所需的一切。快樂學習,別忘了分享!
重點
- 我們指示hibernate連線到mysql資料庫並使用它MySQL5Dialect來生成優化的sql查詢
- spring.jpa.hibernate.ddl-auto=validate 將指示hibernate在應用程式啟動時驗證表模式
- spring.jpa.show-sql=true 將指示hibernate框架記錄控制檯上的所有SQL語句
- 開發人員可以根據需要更改資料來源詳細資訊