Basic program in spring boot .There is only one exception causing failure - java

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

Related

org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet;

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.

Can't find the request for http://localhost:8082/{params}'s Observer

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>

Problem with GraphQL finding method on queryResolver

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

Builder Annotation not working in Java class

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.

Spring boot 2 with embedded postgres - At least one JPA metamodel must be present

The application is a Spring boot v2 application containing the following dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.opentable.components</groupId>
<artifactId>otj-pg-embedded</artifactId>
<version>0.12.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>3.1.7.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
and application.yml contains the configuration for an actual postgres instance, and I've made a single entity
package org.myorg.project.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
#Entity
#Table(name = "SomeEntity")
#Data
#NoArgsConstructor
public class SomeEntity {
#Id
#GeneratedValue
#Column(name = "id")
private Long id;
#Column(name = "someValue")
private String someValue;
}
and a repository
package org.myorg.project.repository;
import org.myorg.project.domain.SomeEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SomeEntityRepository extends JpaRepository<SomeEntity, Long> {
}
Running the application and using the repository and entity works as expected. Database connection is made and entities are persisted, all is well.
Tests... not so much. I want to setup tests to use the OpenTable Embedded PostgreSQL Component so that tests use the same db implementation to avoid headaches and also to be able to test stored procedures and things in-memory db's usually don't provide. I've written a simple test with configuration:
package org.myorg.project.repository;
import com.opentable.db.postgres.junit.EmbeddedPostgresRules;
import com.opentable.db.postgres.junit.SingleInstancePostgresRule;
import org.myorg.project.domain.SomeEntity;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import javax.sql.DataSource;
#RunWith(SpringJUnit4ClassRunner.class)
//#ContextConfiguration(classes = {SomeEntityRepositoryTest.Config.class})
//#ContextConfiguration(loader = AnnotationConfigContextLoader.class)
#SpringBootTest
public class SomeEntityRepositoryTest {
#ClassRule
public static SingleInstancePostgresRule singleInstancePostgresRule = EmbeddedPostgresRules.singleInstance();
#Autowired
private SomeEntityRepository someEntityRepository;
#Test
public void test() {
System.out.println(singleInstancePostgresRule);
System.out.println(singleInstancePostgresRule.getEmbeddedPostgres());
System.out.println(someEntityRepository);
}
#Configuration
#EntityScan(basePackageClasses = SomeEntity.class)
#EnableJpaRepositories(basePackageClasses = SomeEntityRepository.class)
public static class Config {
#Bean
public DataSource dataSource() {
return singleInstancePostgresRule.getEmbeddedPostgres().getPostgresDatabase();
}
}
}
However upon running this test I get an java.lang.IllegalArgumentException: At least one JPA metamodel must be present! exception.
As you can see I have both #EnableJpaRepositories and #EntityScan annotations with configured base package paths. I've tried both the string variant and the class variant but the result is the same.
What am I doing wrong?

Categories