Unable to find a MessageBodyReader - RestEasy / Quarkus - quarkus

I don't know what to do to fix it. When accessing localhost:8080/pets/findByStatusLocal is returning the following error.
Error
Error id 9175b683-f00f-4a8d-9246-a30eb0f8865f-5, javax.ws.rs.ProcessingException: RESTEASY003145: Unable to find a MessageBodyReader of content-type application/json and type interface java.util.List
Pet.java
package org.test;
public class Pet {
private Long id;
private String name;
public Pet() {
this(null, null);
}
public Pet(Long id, String name) {
this.id = id;
this.name = name;
}
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;
}
}
application.properties
org.test.PetService/mp-rest/url=https://petstore.swagger.io/v2/
org.test.PetService/mp-rest/scope=javax.inject.Singleton
PetService.java
package org.test;
import java.util.List;
import java.util.concurrent.CompletionStage;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
#Path("/pet")
#RegisterRestClient
public interface PetService {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("findByStatus")
public List<Pet> findByStatus(#QueryParam("status") String status);
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("findByStatus")
public CompletionStage<List<Pet>> findByStatusAsync(#QueryParam("status") String status);
}
PetResource.java
package org.test;
import java.util.List;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.eclipse.microprofile.rest.client.inject.RestClient;
#Path("/pets")
public class PetResource {
#Inject
#RestClient
PetService petService;
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("findByStatusLocal")
public List<Pet> methodname(#QueryParam("status") String status) {
return petService.findByStatus(status);
}
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("findByStatusLocalAsync")
public CompletionStage<List<Pet>> async(#QueryParam("status") String status) {
return petService.findByStatusAsync(status);
}
}
Is it an error in the source code or could it be in the project configuration?
Thank you very much
*** I made the correction - pom.xml:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest-client-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest-client</artifactId>
</dependency>

You need the quarkus-resteasy-reactive-jackson to write (and read) JSON object. Alternatively, you can also use the -jsonb extension. However, I highly recommend Jackson in this case as it offers many more features.
So, in your pom.xml file, add:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-reactive-jackson</artifactId>
</dependency>

Related

Spring Boot controllers are returning a 404

Spring Boot controllers are returning a 404 on all endpoints
trying to get basic controller returning data
Package structure is setup correctly all packages are sub packages of the main package
annotations look fine been using spring casually for a bit but im clueless im expecting at least hello world im assuming its some spring garbage goin on with it not finding the bean idk no luck finding anything out of conventional configuration. plz help thanks
package com.bookieburglar.api.services;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
//#EnableJpaRepositories(basePackages = "com.bookieburlgar.api.services")
#ComponentScan(basePackages = "com.bookieburglar.api.services")
#SpringBootApplication
public class BookieBurglarApplication {
public static void main(String[] args) {
SpringApplication.run(BookieBurglarApplication.class, args);
}
}
Odds.java
package com.bookieburglar.api.services.models;
import java.util.List;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
#JsonIgnoreProperties(ignoreUnknown = true)
public class Odds {
#Id
#JsonProperty("id")
private String id;
#JsonProperty("sport_key")
private String sport_key;
#JsonProperty("sport_title")
private String sport_title;
#JsonProperty("commence_time")
private String commence_time;
#JsonProperty("home_team")
private String home_team;
#JsonProperty("away_team")
private String away_team;
#JsonProperty("bookmakers")
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "odds_id")
private List<Bookmaker> bookmakers;
public Odds(String id, String sportKey, String sportTitle, String commenceTime,
String homeTeam, String awayTeam, List<Bookmaker> bookmakers) {
this.id = id;
this.sport_key = sportKey;
this.sport_title = sportTitle;
this.commence_time = commenceTime;
this.home_team = homeTeam;
this.away_team = awayTeam;
this.bookmakers = bookmakers;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSportKey() {
return sport_key;
}
public void setSportKey(String sportKey) {
this.sport_key = sportKey;
}
public String getSportTitle() {
return sport_title;
}
public void setSportTitle(String sportTitle) {
this.sport_title = sportTitle;
}
public String getCommenceTime() {
return commence_time;
}
public void setCommenceTime(String commenceTime) {
this.commence_time = commenceTime;
}
public String getHomeTeam() {
return home_team;
}
public void setHomeTeam(String homeTeam) {
this.home_team = homeTeam;
}
public String getAwayTeam() {
return away_team;
}
public void setAwayTeam(String awayTeam) {
this.away_team = awayTeam;
}
public List<Bookmaker> getBookmakers() {
return bookmakers;
}
public void setBookmakers(List<Bookmaker> bookmakers) {
this.bookmakers = bookmakers;
}
}
OddsController
package com.bookieburglar.api.services.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
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.PutMapping;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.bookieburglar.api.services.services.OddsAPIService;
import com.bookieburglar.api.services.services.OddsService;
import com.bookieburglar.api.services.models.Odds;
import com.bookieburglar.api.services.repositories.OddsRepository;
#RestController
#RequestMapping("/Odds")
public class OddsController {
#Autowired
private OddsService oddsService;
#Autowired
private OddsAPIService oddsAPIService;
#GetMapping("/")
public String getOdds() {
return "WORLD";
//return (List<Odds>) OddsRepository.findAll();
}
// #GetMapping("/{id}")
// public Odds getOdds(#PathVariable String id) {
// return OddsRepository.findById(id).orElse(null);
// }
#PostMapping("/create")
public Odds createOdds(#RequestBody Odds Odds) {
System.out.println("frthoo");
return oddsService.saveOdds(Odds);
}
#GetMapping("/refresh")
#ResponseBody
public String refreshOdds() {
System.out.println("ttgb5");
//return oddsAPIService.refreshOdds();
return "yoo";
}
// #PutMapping("/{id}")
// public Odds updateOdds(#PathVariable String id, #RequestBody Odds Odds) {
// Odds.setId(id);
// return OddsRepository.save(Odds);
// }
//
// #DeleteMapping("/{id}")
// public void deleteOdds(#PathVariable String id) {
// OddsRepository.deleteById(id);
// }
}
OddsServices
package com.bookieburglar.api.services.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bookieburglar.api.services.models.Odds;
import com.bookieburglar.api.services.repositories.OddsRepository;
#Service
public class OddsService {
#Autowired
private OddsRepository oddsRepository;
public List<Odds> getAllOdds() {
return (List<Odds>) oddsRepository.findAll();
}
public Optional<Odds> findOddsById(String id) {
return oddsRepository.findById(id);
}
// public List<Odds> findOddsBySportTitle(String sportTitle) {
// return oddsRepository.findBySportTitle(sportTitle);
// }
//
// public List<Odds> findOddsByHomeTeam(String homeTeam) {
// return oddsRepository.findByHomeTeam(homeTeam);
// }
//
// public List<Odds> findOddsByAwayTeam(String awayTeam) {
// return oddsRepository.findByAwayTeam(awayTeam);
// }
public Odds saveOdds(Odds odds) {
return oddsRepository.save(odds);
}
public void deleteOdds(String id) {
oddsRepository.deleteById(id);
}
}
OddsRepository
package com.bookieburglar.api.services.repositories;
import java.util.List;
import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.bookieburglar.api.services.models.Odds;
#Repository
public interface OddsRepository extends JpaRepository<Odds, String> {
List<Odds> findAll();
// additional methods can be defined here, for example, to search for odds by sport key or teams
}
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>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.bookieburglar.api</groupId>
<artifactId>services</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Bookie Burglar</name>
<description>API for BookieBurglar</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
In #ComponentScan annotation. Package name is incorrect.
#ComponentScan(basePackages = "com.bookieburlgar.api.services")
It should be
#ComponentScan(basePackages = "com.bookieburglar.api.services")

Unable to map collection com.bank.model.Customer.account I got this error while running my test case

I got Unable to map collection com.bank.model.Customer.account error while running my controller test case..please give a solution.
I using OneTOMany association b/w customer and Account, here I used List to store the accounts.
I don't know why got this type error I am going share that error too
My controller test
'''
package com.bank.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.bank.model.Account;
import com.bank.model.Customer;
import com.bank.repository.AccountRepository;
import com.bank.service.AccountService;
import com.bank.service.CustomerService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class testController {
#Autowired
private MockMvc mockMvc;
#Autowired
private WebApplicationContext context;
ObjectMapper objectMapper=new ObjectMapper();
#MockBean
private AccountService accountService;
#MockBean
private CustomerService customerService;
#Before
public void setUp() {
mockMvc=MockMvcBuilders.webAppContextSetup(context).build();
}
#Test
public void testCreateCustomer() throws Exception {
Account account=new Account();
account.setAccountNumber(456);
account.setAccountType("savings");
account.setBalance(2000.0);
Customer customer=new Customer();
customer.setCustomerId(1);
customer.setCustomerName("Manasa");
List<Account> acc=new ArrayList<>();
acc.add(account);
String inputInJson=objectMapper.writeValueAsString(customer);
String URI="/customer/createCust";
Mockito.when(customerService.customerCreate(Mockito.any(Customer.class))).thenReturn(customer);
RequestBuilder requestBuilder=MockMvcRequestBuilders
.post(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult result=mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response=result.getResponse();
String outputInJson=response.getContentAsString();
assertThat(outputInJson).isEqualTo(outputInJson);
assertEquals(HttpStatus.OK.value(),response.getStatus()-1);
}
'''
My model are
'''
package com.bank.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Proxy;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name="Customer")
#Proxy(lazy = false)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Integer customerId;
#Column(name="customerName")
String customerName;
#OneToMany( targetEntity=Customer.class,cascade = CascadeType.ALL)
#JoinColumn(name="ca_fk",referencedColumnName = "accountNumber")
private List<Account> account=new ArrayList<>();
public Customer() {
super();
}
public Customer(String customerName, List<Account> account) {
super();
this.customerName = customerName;
this.account = account;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public List<Account> getAccount() {
return account;
}
public void setAccount(List<Account> account) {
this.account = account;
}
#Override
public String toString() {
return "Customer [customerId=" + customerId + ", customerName=" + customerName + ", account=" + account + "]";
}
}
'''
'''
package com.bank.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Proxy;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name="Account")
#Proxy(lazy = false)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Account {
#Id
int accountNumber;
#Column(name="balance")
Double balance;
#Column(name="accountType")
String accountType;
//Customer customer;
public Account() {
super();
}
public Account(int accountNumber, Double balance, String accountType, Customer customer) {
super();
this.accountNumber = accountNumber;
this.balance = balance;
this.accountType = accountType;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public Account(int accountNumber, Double balance, String accountType) {
super();
this.accountNumber = accountNumber;
this.balance = balance;
this.accountType = accountType;
}
}
'''
while running it works fine but issue is only with test cases.
My pom.xml file is
'''
<?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.6.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.bank1</groupId>
<artifactId>bankProjectCapstone-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>bankProjectCapstone-1</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>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</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>
</project>
'''
so far I got this error
'''
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Unable to map collection com.bank.model.Customer.account
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.16.jar:5.3.16]
at
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132) ~[spring-test-5.3.16.jar:5.3.16]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124) ~[spring-test-5.3.16.jar:5.3.16]
Caused by: org.hibernate.AnnotationException: Unable to map collection com.bank.model.Customer.account
at org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1723) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
at org.hibernate.cfg.annotations.CollectionBinder.bindOneToManySecondPass(CollectionBinder.java:944) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
Caused by: org.hibernate.cfg.RecoverableException: Unable to find column with logical name: accountNumber in org.hibernate.mapping.Table(customer) and its related supertables and secondary tables
at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:844) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
at org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:126) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
at org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1713) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
... 102 common frames omitted
Caused by: org.hibernate.MappingException: Unable to find column with logical name: accountNumber in org.hibernate.mapping.Table(customer) and its related supertables and secondary tables
at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:839) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
... 104 common frames omitted
'''

Exception with spring tool

I want to run a simple program with spring tool, but I get so many Exceptions.
1-Application.java
spring.datasource.url=jdbc:mysql://localhost:3306/springbootfirstapp
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=update
2-CustomerController.java
package springbootfirstapp.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import springbootfirstapp.domain.Customer;
import springbootfirstapp.repo.CustomerRepo;
#RestController
#RequestMapping("/customer")
public class CustomerController {
#Autowired
CustomerRepo rp;
#RequestMapping("/findall")
#ResponseBody
public List<Customer> findall(){
return rp.findAll();
}
}
3-Customer.java
package springbootfirstapp.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private int phone;
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 int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
public Customer(int id, String name, int phone) {
super();
this.id = id;
this.name = name;
this.phone = phone;
}
public Customer() {
super();
}
}
4-CustomerRepo.java
package springbootfirstapp.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import springbootfirstapp.domain.Customer;
public interface CustomerRepo extends JpaRepository<Customer, Integer> {
}
5-application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/springbootfirstapp
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=update
6-I add to pom.xml
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
so I am getting the Exception below.
Exception in thread "main" java.lang.StackOverflowError
at org.apache.log4j.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:39)
at org.apache.log4j.LogManager.getLogger(LogManager.java:45)
-------
note: DataBase (springtoolfirstapp) content table (customer) content 3 fields (id-name-phone)
and I create with MySQL workbench..
Please help me. I have tried different approaches and they did not succeed..

Spring Data 3.0.5 MongoDB and ElasticSearch Domain Class mixed Annotation

I'm migrating our application from Spring Boot 1.5.9 to version 2.0.0.
In version 1.5.9 we have successfully used mixed Annotations on several Domain Classes e.g:
...
#org.springframework.data.mongodb.core.mapping.Document(collection = "folder")
#org.springframework.data.elasticsearch.annotations.Document(indexName = "folder")
public class Folder {
...
}
The same approach causes probems in Spring Boot 2.0.0. When MongoDB annotatnion #DBRef is used, Spring throws exception while ElasticsearchRepository creation:
java.lang.IllegalStateException: No association found!
Here comes classes and confs
pom.xml
...
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springfrsamework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
...
<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-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
</dependencies>
...
Application.java
...
#EnableMongoRepositories("com.hydra.sbmr.repoMongo")
#EnableElasticsearchRepositories("com.hydra.sbmr.repoElastic")
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Folder.java (Note this #DBRef couses exception)
package com.hydra.sbmr.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
#org.springframework.data.mongodb.core.mapping.Document(collection = "folder")
#org.springframework.data.elasticsearch.annotations.Document(indexName = "folder")
public class Folder {
#Id
#Getter #Setter private String id;
// Why MongoDB core mapping #DBRef causes java.lang.IllegalStateException: No association found! exception
// while ElasticsearchRepository creation???
#DBRef
#Getter #Setter private Profile profile;
#Getter #Setter private String something;
}
Profile.java
package com.hydra.sbmr.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
#org.springframework.data.mongodb.core.mapping.Document(collection = "profile")
public class Profile {
#Id
#Getter #Setter private String id;
#Getter #Setter String blah;
}
FolderElasticRepository.java
package com.hydra.sbmr.repoElastic;
import com.hydra.sbmr.model.Folder;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface FolderElasticRepository extends ElasticsearchRepository<Folder, String> {
}
You can find whole mini project on GitHub: https://github.com/hydraesb/sbmr
My question:
Is there any solution that will work with mixed Annotatnions on Domain Classes (mongo and elastic) in Spring Boot 2.0.0???
I have the same issue and the solution that i found is to extends SimpleElasticsearchMappingContext like this :
package com.mypackage;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.client.Client;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.EntityMapper;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.io.IOException;
#Configuration
public class ElasticsearchConfiguration {
#Bean
public ElasticsearchTemplate elasticsearchTemplate(Client client, Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) {
return new ElasticsearchTemplate(client, new MappingElasticsearchConverter(new CustomElasticsearchMappingContext()),
new CustomEntityMapper(jackson2ObjectMapperBuilder.createXmlMapper(false).build()));
}
public class CustomEntityMapper implements EntityMapper {
private ObjectMapper objectMapper;
public CustomEntityMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
}
#Override
public String mapToString(Object object) throws IOException {
return objectMapper.writeValueAsString(object);
}
#Override
public T mapToObject(String source, Class clazz) throws IOException {
return objectMapper.readValue(source, clazz);
}
}
}
package com.mypackage;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchPersistentEntity;
import org.springframework.data.mapping.model.Property;
import org.springframework.data.mapping.model.SimpleTypeHolder;
public class CustomElasticsearchMappingContext extends SimpleElasticsearchMappingContext {
#Override
protected ElasticsearchPersistentProperty createPersistentProperty(Property property, SimpleElasticsearchPersistentEntity owner, SimpleTypeHolder simpleTypeHolder) {
return new CustomElasticsearchPersistentProperty(property, owner, simpleTypeHolder);
}
}
package com.mypackage;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchPersistentProperty;
import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.model.Property;
import org.springframework.data.mapping.model.SimpleTypeHolder;
public class CustomElasticsearchPersistentProperty extends SimpleElasticsearchPersistentProperty {
public CustomElasticsearchPersistentProperty(Property property, PersistentEntity owner, SimpleTypeHolder simpleTypeHolder) {
super(property, owner, simpleTypeHolder);
}
#Override
public boolean isAssociation() {
return false;
}
}
I have faced this problem also and I fixed with solution of #ybouraze
#Bean
fun elasticsearchTemplate(client: JestClient, converter: ElasticsearchConverter, builder: Jackson2ObjectMapperBuilder): ElasticsearchOperations {
val entityMapper = CustomEntityMapper(builder.createXmlMapper(false).build())
val mapper = DefaultJestResultsMapper(converter.mappingContext, entityMapper)
return JestElasticsearchTemplate(client, converter, mapper)
}
#Bean
#Primary
fun mappingContext(): SimpleElasticsearchMappingContext {
return MappingContext()
}
#Bean
fun elasticsearchConverter(): ElasticsearchConverter {
return MappingElasticsearchConverter(mappingContext())
}
inner class CustomEntityMapper(private val objectMapper: ObjectMapper) : EntityMapper {
init {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
}
#Throws(IOException::class)
override fun mapToString(`object`: Any): String {
return objectMapper.writeValueAsString(`object`)
}
#Throws(IOException::class)
override fun <T> mapToObject(source: String, clazz: Class<T>): T {
return objectMapper.readValue(source, clazz)
}
}
inner class MappingContext : SimpleElasticsearchMappingContext() {
override fun createPersistentProperty(property: Property, owner: SimpleElasticsearchPersistentEntity<*>, simpleTypeHolder: SimpleTypeHolder): ElasticsearchPersistentProperty {
return PersistentProperty(property, owner, simpleTypeHolder)
}
}
inner class PersistentProperty(property: Property, owner: SimpleElasticsearchPersistentEntity<*>, simpleTypeHolder: SimpleTypeHolder) : SimpleElasticsearchPersistentProperty(property, owner, simpleTypeHolder) {
override fun isAssociation(): Boolean {
return false
}
}

Spring Data ElasticSearch NullPointerException

I have just started with Spring Data ElasticSearch. I have implemented my own repository, but I get a null pointer exception if I try to save an entity. I have got the following code, this is only some test code.
package org.test.elasticsearch.models;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
#Document(indexName = "test", type = "book", shards = 1, replicas = 0)
public class Book {
#Id
private String id;
private String title;
private String author;
public Book(final String id, final String title, final String author) {
this.id = id;
this.title = title;
this.author = author;
}
public String getId() {
return this.id;
}
public void setId(final String id) {
this.id = id;
}
public String getTitle() {
return this.title;
}
public void setTitle(final String title) {
this.title = title;
}
public String getAuthor() {
return this.author;
}
public void setAuthor(final String author) {
this.author = author;
}
}
package org.test.elasticsearch.configs;
import org.elasticsearch.node.NodeBuilder;
import org.test.elasticsearch.repositories.implementations.BookRepositoryImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
#Configuration
#EnableElasticsearchRepositories("org.test.elasticsearch.repositories")
public class ElasticsearchConfiguration {
#Bean
public ElasticsearchOperations elasticsearchTemplate() {
final NodeBuilder nodeBuilder = new NodeBuilder();
return new ElasticsearchTemplate(nodeBuilder.local(true).clusterName("elasticsearch").node().client());
}
#Bean
public BookRepositoryImpl bookRepositoryImplementation() {
return new BookRepositoryImpl();
}
}
package org.test.elasticsearch.repositories;
import org.test.elasticsearch.models.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository;
public interface BookRepository extends ElasticsearchCrudRepository<Book, String>, BookRepositoryCustom {
// query methods
}
package org.test.webapp;
import org.test.elasticsearch.models.Book;
import org.test.elasticsearch.models.Book.BookBuilder;
import org.test.elasticsearch.repositories.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Test {
#Autowired
static BookRepository BookRepository;
public static void main(final String[] args) {
SpringApplication.run(test.class, args);
final Book testBook = new Book("12345", "TestTitle", "TestAuthor");
BookRepository.save(testBook);
}
}
That's my code. And I get the following message after running my spring boot application.
Exception in thread "main" java.lang.NullPointerException
at org.test.webapp.test.main(Test.java:24)
Does anyone have an idea? And another question: When should I use ElasticsearchTemplate with IndexQuery over a custom repository to save my entities?
Your problem is, actually, with Spring Boot: you are not using it properly. Your Test class should look like this (no "static" access to BookRepository and done differently):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.test.elasticsearch.models.Book;
import org.test.elasticsearch.repositories.BookRepository;
#Configuration
#ComponentScan(basePackages = {"org.test.elasticsearch.configs", "org.test.webapp"})
#EnableAutoConfiguration
public class Test implements CommandLineRunner {
#Autowired
private BookRepository bookRepository;
#Override
public void run(String... args) {
final Book testBook = new Book("12345", "TestTitle", "TestAuthor");
bookRepository.save(testBook);
}
public static void main(final String[] args) {
SpringApplication.run(Test.class, args);
}
}
Because, as I see it, you don't want to use a web application, so further you only need these dependencies in pom.xml. Nothing related to spring-boot-web:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>

Resources