Spring Boot Crud操作示例 | Java Code Geeks

19-01-29 banq
                   

,在本教程中,我们将探讨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语句
  • 开发人员可以根据需要更改数据源详细信息

Springbootcrudoperation源码