,在本教程中,我们将探讨spring框架的spring boot模块中的crud操作。
简介
现在,让我们看看如何在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>
这就是本教程的全部内容,我希望这篇文章能为您提供所需的一切。快乐学习,别忘了分享!
重点
Springbootcrudoperation 源码