Ejemplos de Java GraphQL para principiantes [con Spring Boot]

En este artículo, veremos un ejemplo de Java GraphQL y crearemos un servidor GraphQL simple con Spring Boot.





¡A las chicas así les encantan los ejemplos de Java GraphQL con Spring Boot también!



GraphQL es un lenguaje de consulta para API que permite a los clientes consultar la cantidad limitada de datos que necesitan, lo que permite a los clientes recopilar datos en un número limitado de consultas. GraphQL es un protocolo fuertemente tipado y todas las operaciones de datos se validan con el esquema GraphQL.



En este artículo, veremos un ejemplo de Java GraphQL y crearemos un servidor GraphQL simple con Spring Boot.



Adición de dependencias de Maven



Spring Boot .



  1. graphql-spring-boot-starter GraphQL /graphql. GraphQLSchema .
  2. graphql-java GraphQL, .
  3. graphiql-spring-boot-starter , GraphQL .



        <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphql-spring-boot-starter</artifactId>
            <version>5.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphql-java-tools</artifactId>
            <version>5.2.4</version>
        </dependency>
        <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphiql-spring-boot-starter</artifactId>
            <version>5.0.2</version>
        </dependency>


    POM.



    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.techshard.graphql</groupId>
    <artifactId>springboot-graphql</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath />
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphql-spring-boot-starter</artifactId>
            <version>5.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphql-java-tools</artifactId>
            <version>5.2.4</version>
        </dependency>
        <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphiql-spring-boot-starter</artifactId>
            <version>5.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <optional>true</optional>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    </project>


    JPA



    Vehicle JPA . Lombok, , , .





    package com.techshard.graphql.dao.entity;
    import lombok.Data;
    import lombok.EqualsAndHashCode;
    import javax.persistence.*;
    import java.io.Serializable;
    import java.time.LocalDate;
    @Data
    @EqualsAndHashCode
    @Entity
    public class Vehicle implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @Column(name = "ID", nullable = false)
        @GeneratedValue(strategy = GenerationType.AUTO)
        private int id;
        @Column(name = "type", nullable = false)
        private String type;
        @Column(name = "model_code", nullable = false)
        private String modelCode;
        @Column(name = "brand_name")
        private String brandName;
        @Column(name = "launch_date")
        private LocalDate launchDate;
        private transient  String formattedDate;
        // Getter and setter
        public String getFormattedDate() {
            return getLaunchDate().toString();
        }
    }


    JPA.



    package com.techshard.graphql.dao.repository;
    import com.techshard.graphql.dao.entity.Vehicle;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    @Repository
    public interface VehicleRepository extends JpaRepository<Vehicle, Integer> {
    }


    GraphQL



    GraphQL GraphQL, Schema Definition Language (SDL — ). API, .



    GraphQL :



    type Vehicle {
    id: ID!,
    type: String,
    modelCode: String,
    brandName: String,
    launchDate: String
    }
    type Query {
    vehicles(count: Int):[Vehicle]
    vehicle(id: ID):Vehicle
    }
    type Mutation {
    createVehicle(type: String!, modelCode: String!, brandName: String, launchDate: String):Vehicle
    }


    graphql src/main/resources vehicleql.graphqls. vehicleql.graphqls. , . , .graphqls.



    . GraphQL , , .



    Vehicle, . Query , GraphQL . , , . . GraphQL, .



    .



    Mutation , .



    Root Query



    Query Mutation GraphQL. . (resolver) GraphQLQueryResolver GraphQLMutationResolver. , .



    Vehicle.



    package com.techshard.graphql.query;
    import com.coxautodev.graphql.tools.GraphQLQueryResolver;
    import com.techshard.graphql.dao.entity.Vehicle;
    import com.techshard.graphql.service.VehicleService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import java.util.List;
    import java.util.Optional;
    @Component
    public class VehicleQuery implements GraphQLQueryResolver {
        @Autowired
        private VehicleService vehicleService;
        public List<Vehicle> getVehicles(final int count) {
            return this.vehicleService.getAllVehicles(count);
        }
        public Optional<Vehicle> getVehicle(final int id) {
            return this.vehicleService.getVehicle(id);
        }
    }


    Vehicle Vehicle. , .



    .



    package com.techshard.graphql.mutation;
    import com.coxautodev.graphql.tools.GraphQLMutationResolver;
    import com.techshard.graphql.dao.entity.Vehicle;
    import com.techshard.graphql.service.VehicleService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import java.time.LocalDate;
    @Component
    public class VehicleMutation implements GraphQLMutationResolver {
        @Autowired
        private VehicleService vehicleService;
        public Vehicle createVehicle(final String type, final String modelCode, final String brandName, final String launchDate) {
            return this.vehicleService.createVehicle(type, modelCode, brandName, launchDate);
        }
    }


    Vehicle, Mutation .



    , .



    package com.techshard.graphql.service;
    import com.techshard.graphql.dao.entity.Vehicle;
    import com.techshard.graphql.dao.repository.VehicleRepository;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import java.time.LocalDate;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors;
    @Service
    public class VehicleService {
        private final VehicleRepository vehicleRepository ;
        public VehicleService(final VehicleRepository vehicleRepository) {
            this.vehicleRepository = vehicleRepository ;
        }
        @Transactional
        public Vehicle createVehicle(final String type,final String modelCode, final String brandName, final String launchDate) {
            final Vehicle vehicle = new Vehicle();
            vehicle.setType(type);
            vehicle.setModelCode(modelCode);
            vehicle.setBrandName(brandName);
            vehicle.setLaunchDate(LocalDate.parse(launchDate));
            return this.vehicleRepository.save(vehicle);
        }
        @Transactional(readOnly = true)
        public List<Vehicle> getAllVehicles(final int count) {
            return this.vehicleRepository.findAll().stream().limit(count).collect(Collectors.toList());
        }
        @Transactional(readOnly = true)
        public Optional<Vehicle> getVehicle(final int id) {
            return this.vehicleRepository.findById(id);
        }
    }




    . Spring Boot : http://localhost:8080/graphiql. , .





    .





    .



    mutation {
      createVehicle(type: "car", modelCode: "XYZ0192", brandName: "XYZ", launchDate: "2016-08-16") 
      {
        id
      }
    }


    Vehicle. :



    {
      "data": {
        "createVehicle": {
          "id": "1"
        }
      }
    }


    , .



    query {
      vehicles(count: 1) 
      {
        id, 
        type, 
        modelCode
    }
    }


    :



    {
      "data": {
        "vehicles": [
          {
            "id": "1",
            "type": "bus",
            "modelCode": "XYZ123"
          }
        ]
      }
    }


    , , , .





    GraphQL Java Spring Boot. .



    GitHub.





    Introduction to GraphQL



    GraphQL: Core Features, Architecture, Pros, and Cons



    GraphQL, , GraphQL.



    . .

    « GraphQL »



All Articles