Using Spring Data JPA's Spring Boot

In this tutorial, gifted class small sharp U will take you to see the Spring Data JPA how DAO provides complete abstraction layer. We no longer need to DAO write an implementation layer; the Spring the Data automatically generated to achieve DAO implementation.


Dependent on configuration

In this tutorial, I will MySQL database with Spring Data used together. This is build.gradle file:

buildscript {
    ext {
        springBootVersion = '2.1.0.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.amitph.spring'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
    mavenCentral()
}
dependencies {
    implementation('org.springframework.boot:spring-boot-starter-web')
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile('mysql:mysql-connector-java:8.0.13')
    testImplementation('org.springframework.boot:spring-boot-starter-test')
}

 

Data source configuration

Now that we have configured the dependencies. Now do not tell which to connect to the data source. This is me with Spring Boot data source entry application.yml .

spring:
  datasource:
    url: jdbc:mysql://localhost:33099/dogs
    password: <ENTER _ PASSWORD _ HERE >
    username: root
    driver-class-name: "com.mysql.jdbc.Driver"
  jpa:
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    hibernate:
      ddl-auto: update

 

Here we have the designated JDBC the URL of , user name, password, and driver class name (MySQL) .


In addition, there JPA specific configuration. The first is the database platform, it tells us that the MySQL basis for the next dialect inquiry to consider Hibernate function. In this way, all database operations will MySQL specific syntax processing. The second JPA configuration is the DDL-Auto , which tells Hibernate to create their own database and table structure (if not already exist).


When enabled, Hibernate will be based on the entity Bean to create the database structure and data sources.


Entity Bean

We will do a first-level code is written in the Entity Bean . This is the Oracle documentation for the entity Bean content.


Use JPA , you can use any POJO class as JPA entities - from using JPA persistence providers (in Java EE EJB inside the container or external) to obtain an entity manager service, which is non-transient fields should be persisted to the relationship database of Java objects. Java SE application EJB container).


In simple words, JPA entity is any the Java POJO , can indicate the underlying table structure. Because our services based on the " Dog" table, we will create a " Dog" physical object.

package com.amitph.spring.dogs.repo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Dog {
    @Id
    @GeneratedValue
    private long id;
    private String name;
    private int age;
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

 

上面的POJO@Entity注释,表示这是表名Dog的实体对象。


然后,有三个字段代表数据表列。字段ID是我们的主键,因此被标记为@Id


字段ID也用@GeneratedValue标记,表示这是一个自动增量列,Hibernate将负责输入下一个值。Hibernate首先将查询基础表以了解该列的最大值,并在下一次插入时对其进行递增。这也意味着我们不需要为Id列指定任何值,可以将其留空。


仓库接口


存储库代表DAO层,通常执行所有数据库操作。感谢Spring Data,他提供了这些方法的实现。让我们看看我们的DogsRepoisitory,它扩展了CrudRepository

package com.amitph.spring.dogs.repo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface DogsRepository extends CrudRepository<Dog, Long> {}

 

DogsRepository中这里没有方法声明。这是因为Spring DataCrudInterface 已经声明了基本的CRUD方法。


在这里,我们完成了JPASpring数据工作——换句话说,就是DAO层。现在,让我们编写一个简单的服务层和一个控制器。


控制器和服务层

完成数据访问层后,我们将编写控制器和服务层。请注意,DogsRepository带有@Repository注释,这也将其添加到Spring Context中。现在,我们可以在Service中自动连线存储库。

Dogs Service

此类具有简单的CRUD方法。还将Entity Bean转换为DTO(数据传输对象)。DTO还是一个简单的Java POJO,用于在系统之间传输数据。在这里,我们从REST端点返回DTO

package com.amitph.spring.dogs.service;

import com.amitph.spring.dogs.model.DogDto;
import com.amitph.spring.dogs.repo.Dog;
import com.amitph.spring.dogs.repo.DogsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
@Component
public class DogsService {
    @Autowired DogsRepository repository;
    public void add(DogDto dto) {
        repository.save(toEntity(dto));
    }
    public void delete(long id) {
        repository.deleteById(id);
    }
    public List<Dog> getDogs() {
        return (List<Dog>) repository.findAll();
    }
    public Dog getDogById(long id) {
        Optional<Dog> optionalDog = repository.findById(id);
        return optionalDog.orElseThrow(() -> new DogNotFoundException("Couldn't find a Dog with id: " + id));
    }
    private Dog toEntity(DogDto dto) {
        Dog entity = new Dog();
        entity.setName(dto.getName());
        entity.setAge(dto.getAge());
        return entity;
    }
}

 

Dogs控制器

Dogs Controller是具有简单CRUD端点的标准REST控制器。控制器的工作是处理HTTP请求并调用Service类方法。

package com.amitph.spring.dogs.web;
import com.amitph.spring.dogs.model.DogDto;
import com.amitph.spring.dogs.repo.Dog;
import com.amitph.spring.dogs.service.DogsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/dogs")
public class DogsController {
    @Autowired DogsService service;
    @GetMapping
    public List<Dog> getDogs() {
        return service.getDogs();
    }
    @PostMapping
    public void postDogs(@RequestBody DogDto dto) {
        service.add(dto);
    }
    @GetMapping("/{id}")
    public Dog getById(@PathVariable(required = true) long id) {
        return service.getDogById(id);
    }
    @DeleteMapping("/{id}")
    public void delete(@PathVariable(required = true) long id) {
        service.delete(id);
    }
}

 

现在,Dogs Service已准备好运行。启动应用程序并执行HTTP端点。


结论

Spring数据和JPA教程的Spring Boot到此结束。我们看到了如何将Spring Data的抽象用于数据访问层。我们看到了如何以Entity Bean的形式表示数据库表,以及如何使用Spring Data的自动生成的存储库实现。此外,我们还看到了如何使用Spring Boot进行自动数据源配置。


Spring Boot Rest Service帖子中,我们已经看到了使用Spring Boot创建RESTful Web服务。在当前文章中,我们不关心异常处理。访问Spring Rest Service异常处理以了解有关处理异常的信息。我们还跳过了这里的单元测试部分,这将在以后的文章中介绍。

 


Guess you like

Origin blog.51cto.com/14631216/2458301