This code was written for learnig purpose.
#Builder and #Data annotation has been implemented in the Book class. While trying to create a builder for the same in LibraryApplication.java builder is not being recognized.
How can I enable the annotations which on Book class
**Edit **: When trying to compile below error is generated.
java.lang.Error: Unresolved compilation problem: The method builder() is undefined for the type Book at com.baeldung.LibraryApplication$DataSetup.run(LibraryApplication.java:25)
Also I am using STS implementation of eclipse. I have checked whether the same code works in eclilpse Oxygen but the same error is thrown
Note: The project is created in Spring Boot
Book.class
package com.baeldung.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#NoArgsConstructor
#Builder
#Entity
#AllArgsConstructor
public class Book {
#Id
#GeneratedValue
private Long id;
#NotNull
String name, isbn;
}
LibraryApplication.java
package com.baeldung;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import com.baeldung.domain.Book;
import com.baeldung.repo.BookingRespository;
#SpringBootApplication
public class LibraryApplication {
#Autowired
private BookingRespository bookingRespository;
#Component
class DataSetup implements ApplicationRunner{
#Override
public void run(ApplicationArguments args) throws Exception {
// bookingRespository.save(Book.builder().name("Way of Kings").isbn("123").build());
}
}
public static void main(String[] args) {
SpringApplication.run(LibraryApplication.class, args);
}
}
BookingRepository.java
package com.baeldung.repo;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import com.baeldung.domain.Book;
#RepositoryRestResource(path="books",collectionResourceRel="books")
public interface BookingRespository extends PagingAndSortingRepository<Book, Long>{
}
pom.xml
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.baeldung</groupId>
<artifactId>library</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>library</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.0.1-jre</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
As per suggestion by #f1sh - If you use mvn package, this should work. But to get it to work in your IDE (which is probably where you get this error), you need to install lombok into eclipse: projectlombok.org/setup/eclipse
Installing the Lombok plugin in our IDE is necessary in order to use any annotations from Lombok. I sincerely hope it works for you. and You won't run into any issues.
Related
I am writing a unit test for a custom query in my repository in Spring. I am using an h2 in-memory database to create an employee and perform an assertion on that employee which should be returned from the custom query.
When I call the save method from my repository the following error is thrown:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
I will include my pom.xml as well as the code for my repository and test.
Unit Test
package com.stg.mlindow.javabootrestcert.stgbootrestcert.employee;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
#AutoConfigureTestDatabase
#ActiveProfiles("test")
#TestPropertySource(locations = "classpath:application-test.properties")
#DataJpaTest
class EmployeeRepositoryTest {
#Autowired
private EmployeeRepository employeeRepository;
#Test
void findAllByBossId() {
Employee employee = new Employee(
"CEO",
"Bruce",
"Wayne",
null
);
employeeRepository.save(employee);
List<Employee> employees = employeeRepository.findAllByBossId(null);
List<Employee> expected = new ArrayList<Employee>() {
{
add(employee);
}
};
assertIterableEquals(expected, employees);
}
}
Pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.stg.mlindow.javabootrestcert</groupId>
<artifactId>stg-boot-rest-cert</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>stg-boot-rest-cert</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>23.1.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application-test.properties
##### Database #####
spring.datasource.url=jdbc:h2://mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
Repository
package com.stg.mlindow.javabootrestcert.stgbootrestcert.employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
#Repository
public interface EmployeeRepository extends JpaRepository<Employee, BigInteger>,
PagingAndSortingRepository<Employee, BigInteger> {
List<Employee> findAllByBossId(BigInteger bossId);
}
I have tried the suggestion in this question but it did not fix my problem. I was expecting the test to create an Employee and then try to retrieve that newly created employee from the h2 database by boss id. Then it would assert that the 2 lists are equal.
I resolved this issue by fixing an error in my application-test.
##### Database #####
spring.datasource.url=jdbc:h2://mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
The spring.jpa.properties.hibernate.dialect needed to be set to the H2Dialect rather than the PostgreSQLDialect.
This was as #Lesiak suspected.
I have a very simple Java REST service code concept here.
The problem is that when I am hitting the URL the below message is showing up in the console:
Can't find the request for http://localhost:8082/REST/services/patientservices/getallpatients's Observer
I am using cxf.jaxrs.component-scan=true for spring to read the annotations.
Below are the classes and configuration file:
pom.xml:
<?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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.11.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.mayukh.rs</groupId>
<artifactId>jaxrs</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jaxrs</name>
<description>JAX RS</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
PatientService.java:
package com.mayukh.rs;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import com.mayukh.rs.model.Patient;
#Path("/patientservices")
public interface PatientService {
#Path("/getallpatients")
#GET
List<Patient> getPatients();
}
PatientServiceImpl.java:
package com.mayukh.rs;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.mayukh.rs.model.Patient;
#Service
public class PatientServiceImpl implements PatientService {
Map<Long, Patient> patients = new HashMap<>();
long currId = 123;
public PatientServiceImpl() {
init();
}
public void init() {
Patient patient = new Patient();
patient.setId(currId);
patient.setName("Mayukh");
patients.put(patient.getId(), patient);
}
#Override
public List<Patient> getPatients() {
Collection<Patient> results = patients.values();
List<Patient> response = new ArrayList<>(results);
return response;
}
}
application.properties:
server.port=8082
cxf.jaxrs.component-scan=true
server.servlet.context-path=/REST
There was a mistake in the pom.xml file.
Instead of jaxws dependency it should be jaxrs dependency.
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxrs</artifactId>
<version>3.4.3</version>
</dependency>
I am building a simple url shortener connected to MongoDB Atlas with a JPA repository, and when I try to save the url data when the request hits the post request, I get the following error: java.lang.NoSuchMethodError: com.mongodb.client.MongoCollection.insertOne(Ljava/lang/Object;)Lcom/mongodb/client/result/InsertOneResult;. According the research, I believe it is a dependency issue but was not able to resolve it.
URL.java:
package com.sideproject.urlshortner.model;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Data
#Document(collection = "url")
public class URL {
#Id
private String id;
String longURL;
String shortenedURL;
public URL(String longURL, String shortenedURL) {
this.longURL = longURL;
this.shortenedURL = shortenedURL;
}
}
URLController.java:
package com.sideproject.urlshortner.controller;
import com.sideproject.urlshortner.repository.URLRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import com.sideproject.urlshortner.model.URL;
#RestController
#RequestMapping("/index")
public class URLController {
#Autowired
private URLRepository urlRepository;
#RequestMapping(value="/urls/", method=RequestMethod.POST)
public URL postURL(#RequestBody URL url) {
return urlRepository.save(url); // giving the error.
}
}
application.properties:
spring.data.mongodb.uri=mongodb+srv://myname:password#testcluster-scgty.mongodb.net/dbname?retryWrites=true&w=majority
spring.data.mongodb.database=dbname
pom.xml:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sideproject</groupId>
<artifactId>url-shortner</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>url-shortner</name>
<properties>
<java.version>1.8</java.version>
</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-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Any help would be greatly appreciated!
The issue is you are providing boot starter and mongo driver like below.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.6</version>
</dependency>
whereas spring-boot-starter-data-MongoDB has a java driver dependency of 4.0.4. So 2 different versions are colliding. just remove your explicit mongo driver dependency.
<properties>
<project.type>multi</project.type>
<dist.id>spring-data-mongodb</dist.id>
<springdata.commons>2.3.1.RELEASE</springdata.commons>
<mongo>4.0.4</mongo>
<mongo.reactivestreams>${mongo}</mongo.reactivestreams>
<jmh.version>1.19</jmh.version>
</properties>
One of the features of spring-boot-starter-parent is that it manages versions of many common dependencies for you, ensuring that the versions of all the different pieces you're using are compatible. In this case, your explicit version is causing incompatibility between Spring Data MongoDB and the MongoDB driver; simply eliminate the version tags from your dependencies.
(You may be getting a warning about "overriding managed dependency version"; always pay attention to warnings.)
I'm working on a GraphQL java API project and i'm having problems with the Query not finding the methods in the Query.java (QueryResolver)
I can't see an error on this code but aparently it has one ':D
PS: I use java open JDK 11
the error: (full stacktrace on https://pastebin.com/cpVRpdsj)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.servlet.ServletRegistrationBean]: Factory method 'graphQLServlet' threw exception; nested exception is com.coxautodev.graphql.tools.FieldResolverError: No method or field found with any of the following signatures (with or without one of [interface graphql.schema.DataFetchingEnvironment] as the last argument), in priority order:
com.example.GraphQLRProject.core.Query.findAllPessoas()
com.example.GraphQLRProject.core.Query.getFindAllPessoas()
com.example.GraphQLRProject.core.Query.findAllPessoas
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
... 59 common frames omitted
my pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>GraphQLRProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>GraphQLRProject</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<!--<kotlin.version>1.3.10</kotlin.version> -->
</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>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
-->
<!--
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>6.0.1</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>graphql-java</artifactId>
<version>11.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java-servlet</artifactId>
<version>6.1.3</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>5.0.2</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.6</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<!-- GraphQL end -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
my Query.java
package com.example.GraphQLRProject.core;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.coxautodev.graphql.tools.GraphQLQueryResolver;
import com.example.GraphQLRProject.model.Pessoa;
import com.example.GraphQLRProject.repository.PessoaRepository;
#Component
public class Query implements GraphQLQueryResolver {
#Autowired
PessoaRepository pessoaRepository;
List<Pessoa> findAllPessoas() {
return pessoaRepository.findAll();
}
}
my main application
package com.example.GraphQLRProject;
import java.util.TimeZone;
import javax.annotation.PostConstruct;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.coxautodev.graphql.tools.SchemaParser;
import com.example.GraphQLRProject.core.Mutation;
import com.example.GraphQLRProject.core.Query;
import com.example.GraphQLRProject.util.DateScalar;
import graphql.schema.GraphQLSchema;
import graphql.servlet.SimpleGraphQLHttpServlet;
#ComponentScan(basePackageClasses = GraphQlrProjectApplication.class)
#SpringBootApplication(scanBasePackages = "com.example")
#EntityScan("com.example")
#EnableJpaRepositories("com.example")
#SuppressWarnings({"rawtypes", "unchecked"})
public class GraphQlrProjectApplication {
public static void main(String[] args) {
SpringApplication.run(GraphQlrProjectApplication.class, args);
}
#PostConstruct
void started() {
TimeZone.setDefault(TimeZone.getTimeZone("America/Recife"));
}
#Bean
public ServletRegistrationBean graphQLServlet() {
return new ServletRegistrationBean(SimpleGraphQLHttpServlet.newBuilder(buildSchema()).build(), "/graphql");
}
private static GraphQLSchema buildSchema() {
return SchemaParser
.newParser()
.file("schema.graphqls")
.resolvers(new Query(), new Mutation())
.scalars(DateScalar.DATE)
.build()
.makeExecutableSchema();
}
}
and my schema.graphqls
schema {
query: Query
mutation: Mutation
}
type Query {
findAllPessoas: [Pessoa]
}
type Mutation {
savePessoa(novo: PessoaInput): Pessoa
}
type Pessoa {
id: ID!
nome: String!
cpf: String!
email: String!
}
input PessoaInput{
nome: String!
cpf: String!
email: String!
}
The problem was that the method was not public ...
big facepalm for me ':D
Ticket.java
package com.mysql.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
#Entity
#Table(name= "Ticket")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#ToString
public class Ticket {
#Id
#GeneratedValue
private int id;
private double amount;
private String category;
}
ticketdao
package com.mysql.dao;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import com.mysql.model.Ticket;
public interface TicketDao extends CrudRepository<Ticket, Integer>{
void save(List<Ticket> tickets);
}
Ticketcontroller.java
package com.mysql.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
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 com.mysql.dao.TicketDao;
import com.mysql.model.Ticket;
#RestController
#RequestMapping("/ticket")
public class TicketController {
#Autowired
private TicketDao dao;
#PostMapping("/bookTickets")
public String bookTicket(#RequestBody List<Ticket> tickets) {
dao.save(tickets);
return "tickets booked :" + tickets.size();
}
#GetMapping("/getTickets")
public List<Ticket> getTickets(){
return (List<Ticket>) dao.findAll();
}
}
main program
package com.example.springmysql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringMysqlApplication {
public static void main(String[] args) {
SpringApplication.run(SpringMysqlApplication.class, args);
}
}
I found the same exception in stack overflow to download the jar file.
But i failed when i used the same in my case.It is a simple spring boot mysql crud application.
error appearing when running the program
Caused by: java.net.ConnectException: Connection timed out: connect
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-mysql</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-mysql</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Spring boot jdbc dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<scope>compile</scope>
</dependency>
<!-- MySql dependency -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<scope>compile</scope>
<!-- <version>4.1.4.Final</version> -->
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://169.254.99.155:3306/ticket
spring.datasource.username=root
spring.datasource.password=user789
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MYSQL5Dialect
spring.datasource.tomcat.testWhileIdle = true
spring.datasource.tomcat.timeBetweenEvictionRunsMillis = 60000
spring.datasource.tomcat.validationQuery = SELECT 1