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

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
'''

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")

When I run spring boot test cases I got error I could not resolve on my own

I am creating test cases for my controller
package com.bank.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
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.http.MediaType;
import com.bank.model.Account;
import com.bank.model.Customer;
import com.bank.service.AccountService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
#RunWith(SpringRunner.class)
#WebMvcTest(value=AccountController.class)
class AccountControllerTest{
#Autowired
private MockMvc mockMvc;
#MockBean
private AccountService accountService;
#Test
public void testcreateAccount() throws Exception{
Customer customer=new Customer();
customer.setCustomerId(1);
customer.setCustomerName("Manasa");
Account mockAccount=new Account();
mockAccount.setAccountNumber(456);
mockAccount.setBalance(2000.0);
mockAccount.setAccountType("savings");
mockAccount.setCustomer(customer);
String inputInJson=this.mapToJson(mockAccount);
String URI="/account";
Mockito.when(accountService.accountCreate(Mockito.any(Account.class))).thenReturn(mockAccount);
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());
}
#Test
public void testaccountList() throws Exception{
Customer customer1=new Customer();
customer1.setCustomerId(1);
customer1.setCustomerName("Manasa");
Account mockAccount1=new Account();
mockAccount1.setAccountNumber(456);
mockAccount1.setAccountType("savings");
mockAccount1.setBalance(2000.0);
mockAccount1.setCustomer(customer1);
Customer customer2=new Customer();
customer2.setCustomerId(2);
customer2.setCustomerName("Madhu");
Account mockAccount2=new Account();
mockAccount2.setAccountNumber(789);
mockAccount2.setAccountType("savings");
mockAccount2.setBalance(6000.0);
mockAccount2.setCustomer(customer2);
Customer customer3=new Customer();
customer3.setCustomerId(3);
customer3.setCustomerName("Lalasa");
Account mockAccount3=new Account();
mockAccount3.setAccountNumber(123);
mockAccount3.setAccountType("savings");
mockAccount3.setBalance(50000.0);
mockAccount3.setCustomer((Customer)Arrays.asList(3,"Lalasa"));
List<Account> accountList=new ArrayList<>();
accountList.add(mockAccount1);
accountList.add(mockAccount2);
accountList.add(mockAccount3);
Mockito.when(accountService.allAccounts()).thenReturn(accountList);
String URI="/account/aclist";
RequestBuilder requestBuilder=MockMvcRequestBuilders.get(
URI).accept(MediaType.APPLICATION_JSON);
MvcResult result=mockMvc.perform(requestBuilder).andReturn();
String expectedJson=this.mapToJson(accountList);
String outputInJson=result.getResponse().getContentAsString();
assertThat(outputInJson).isEqualTo(expectedJson);
}
#Test
public void testbyAccountType() throws Exception{
Customer customer=new Customer();
customer.setCustomerId(1);
customer.setCustomerName("Manasa");
Account mockAccount=new Account();
mockAccount.setAccountNumber(456);
mockAccount.setAccountType("savings");
mockAccount.setBalance(2000.0);
mockAccount.setCustomer(customer);
String expectedJson=this.mapToJson(mockAccount);
Mockito.when(accountService.accountByType(Mockito.anyString())).thenReturn((List<Account>) mockAccount);
String URI="/account//byType/savings";
RequestBuilder requestBuilder=MockMvcRequestBuilders.get(
URI).accept(MediaType.APPLICATION_JSON);
MvcResult result=mockMvc.perform(requestBuilder).andReturn();
String outputInJson=result.getResponse().getContentAsString();
assertThat(outputInJson).isEqualTo(expectedJson);
}
private String mapToJson(Object object) throws JsonProcessingException{
ObjectMapper objectMapper=new ObjectMapper();
return objectMapper.writeValueAsString(object);
}
}
My Controller class is
package com.bank.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;
import com.bank.model.Account;
import com.bank.service.AccountService;
import com.bank.Exception.ResourceNotFoundException;
#RestController
#RequestMapping("/account")
public class AccountController {
#Autowired
AccountService accountService;
#PostMapping
public ResponseEntity<?> createAccount(#RequestBody Account account) throws ResourceNotFoundException{
Account acc=accountService.accountCreate(account);
if(acc!=null) {
return new ResponseEntity<>(acc,HttpStatus.CREATED);
}else {
throw new ResourceNotFoundException("Account is not Created!!");
}
}
#GetMapping("/aclist")
public ResponseEntity<?> accountList() throws ResourceNotFoundException{
List<Account> accountList=accountService.allAccounts();
if(!(accountList.isEmpty())) {
return new ResponseEntity<>(accountList,HttpStatus.OK);
}else {
throw new ResourceNotFoundException("accounts not found");
}
}
#GetMapping("/byType/{accountType}")
public ResponseEntity<?> byAccountType(#PathVariable String accountType) throws ResourceNotFoundException{
List<Account> account =accountService.accountByType(accountType);
if(account.isEmpty()) {
throw new ResourceNotFoundException(accountType+""+"Type of account does not exist!!");
}else {
return new ResponseEntity<>(account,HttpStatus.OK);
}
}
#GetMapping("/{accountNumber}")
public ResponseEntity<?> getAccountById(#PathVariable("accountNumber") int accountNumber) throws ResourceNotFoundException{
Account acc=accountService.findAccountById(accountNumber);
if(acc!=null) {
return new ResponseEntity<>(acc,HttpStatus.OK);
}else {
throw new ResourceNotFoundException("account [accountNumber="+accountNumber+"] can't be found");
}
}
#PutMapping("/{from}/{to}/{amount}")
public ResponseEntity<?> transferFunds(#PathVariable("from") int from,#PathVariable("to") int to,#PathVariable("amount") double amount) throws ResourceNotFoundException{
return accountService.transferFunds(from, to, amount);
}
#DeleteMapping("/{accountNumber}")
public ResponseEntity<?> deleteAccById(#PathVariable ("accountNumber") int accountNumber) throws ResourceNotFoundException{
String x=accountService.deleteById(accountNumber);
if(x.equalsIgnoreCase("deleted")){
return new ResponseEntity<>("deleted successfully",HttpStatus.OK);
}else {
throw new ResourceNotFoundException("Account [accountNumber="+accountNumber+"] can't be found");
}
}
#GetMapping("/balance/{accountNumber}")
public ResponseEntity<?> getBalanceById(#PathVariable ("accountNumber") int accountNumber) throws ResourceNotFoundException{
String balance=accountService.getBalanceById(accountNumber);
if(balance.equalsIgnoreCase("Invalid accountNumber")) {
throw new ResourceNotFoundException("Account [accountNumber="+accountNumber+"] can't be found");
}else {
return new ResponseEntity<>(balance,HttpStatus.OK);
}
}
#DeleteMapping("/deleteAll")
public ResponseEntity<?> deleteAllAccounts(){
return new ResponseEntity<>(accountService.deleteAllAccounts(),HttpStatus.OK);
}
#PutMapping("/update/{accountNumber}")
public ResponseEntity<?> UpdateAccount(#PathVariable ("accountNumber") int accountNumber,#RequestBody Account account) throws ResourceNotFoundException{
Account acc=accountService.updateAccount(accountNumber, account);
if(acc!=null) {
return new ResponseEntity<>(acc,HttpStatus.OK);
}else {
throw new ResourceNotFoundException("invalid accountNumber and account");
}
}
#PutMapping("/deposite/{amount}/{accountNumber}")
public ResponseEntity<?> deposite(#PathVariable("amount") double amount,#PathVariable("accountNumber") int accountNumber) throws ResourceNotFoundException{
return accountService.deposite(amount,accountNumber);
}
#PutMapping("/withdraw/{amount}/{accountNumber}")
public ResponseEntity<?> withDraw(#PathVariable("amount") double amount,#PathVariable("accountNumber") int accountNumber) throws ResourceNotFoundException{
return accountService.withdraw(amount,accountNumber);
}
}
My model class is (has many to one relations with customer class)
package com.bank.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Proxy;
#Entity
#Table(name="Account")
#Proxy(lazy = false)
public class Account {
#Id
int accountNumber;
#Column(name="balance")
Double balance;
#Column(name="accountType")
String accountType;
#ManyToOne( targetEntity=Customer.class,cascade = CascadeType.ALL)
#JoinColumn(name="ca_fk",referencedColumnName = "customerId")
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;
this.customer = customer;
}
#Override
public String toString() {
return "Account [accountNumber=" + accountNumber + ", balance=" + balance + ", accountType=" + accountType
+ ", customer=" + customer + "]";
}
public Integer 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 Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
customer class
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;
#Entity
#Table(name="Customer")
#Proxy(lazy = false)
public class Customer {
#Id
Integer customerId;
#Column(name="customerName")
String customerName;
public Customer() {
super();
}
public Customer(int customerId, String customerName) {
super();
this.customerId = customerId;
this.customerName = customerName;
}
#Override
public String toString() {
return "Customer [customerId=" + customerId + ", customerName=" + customerName + "]";
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
I got the below error
MockHttpServletRequest:
HTTP Method = POST
Request URI = /account
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"114"]
Body = {"accountNumber":456,"balance":2000.0,"accountType":"savings","customer":{"customerId":1,"customerName":"Manasa"}}
Session Attrs = {}
Handler:
Type = com.bank.controller.AccountController
Method = com.bank.controller.AccountController#createAccount(Account)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 201
Error message = null
Headers = [Content-Type:"application/json"]
Content type = application/json
Body = {"accountNumber":456,"balance":2000.0,"accountType":"savings","customer":{"customerId":1,"customerName":"Manasa"}}
Forwarded URL = null
Redirected URL = null
Cookies = []
2022-03-20 02:11:12.422 WARN 12996 --- [ main] o.s.test.context.TestContextManager : Caught exception while invoking 'afterTestMethod' callback on TestExecutionListener [org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#485e36bc] for test method [public void com.bank.controller.AccountControllerTest.testbyAccountType() throws java.lang.Exception] and test instance [com.bank.controller.AccountControllerTest#153cfd86]
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.bank.controller.AccountControllerTest.testbyAccountType(AccountControllerTest.java:139)
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, which is not supported
3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed
at org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener.resetMocks(ResetMocksTestExecutionListener.java:83) ~[spring-boot-test-2.6.4.jar:2.6.4]
at org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener.resetMocks(ResetMocksTestExecutionListener.java:70) ~[spring-boot-test-2.6.4.jar:2.6.4]
at org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener.afterTestMethod(ResetMocksTestExecutionListener.java:64) ~[spring-boot-test-2.6.4.jar:2.6.4]
at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:445) ~[spring-test-5.3.16.jar:5.3.16]
at org.springframework.test.context.junit.jupiter.SpringExtension.afterEach(SpringExtension.java:206) ~[spring-test-5.3.16.jar:5.3.16]
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAfterEachCallbacks$12(TestMethodTestDescriptor.java:257) ~[junit-jupiter-engine-5.8.2.jar:5.8.2]
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAllAfterMethodsOrCallbacks$13(TestMethodTestDescriptor.java:273) ~[junit-jupiter-engine-5.8.2.jar:5.8.2]
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.8.2.jar:1.8.2]
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAllAfterMethodsOrCallbacks$14(TestMethodTestDescriptor.java:273) ~[junit-jupiter-engine-5.8.2.jar:5.8.2]
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) ~[na:na]
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAllAfterMethodsOrCallbacks(TestMethodTestDescriptor.java:272) ~[junit-jupiter-engine-5.8.2.jar:5.8.2]
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAfterEachCallbacks(TestMethodTestDescriptor.java:256) ~[junit-jupiter-engine-5.8.2.jar:5.8.2]
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:141) ~[junit-jupiter-engine-5.8.2.jar:5.8.2]
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66) ~[junit-jupiter-engine-5.8.2.jar:5.8.2]
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151) ~[junit-platform-engine-1.8.2.jar:1.8.2]
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.8.2.jar:1.8.2]
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.8.2.jar:1.8.2]
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.8.2.jar:1.8.2]
My pom.xml 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.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.bank</groupId>
<artifactId>capstoneBankProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>capstoneBankProject</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
<junit.version>4.13.1</junit.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>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</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>
<!-- exclude junit 4 -->
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Junit 5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
my project structure
You are casting mockAccount to a list without it actually being a list, that's probably why the mock fails.

Consider defining a bean of type 'javax.persistence.EntityManager' in your configuration

I am a beginner to spring. So right now I am starting to learn spring boot and build this simple project, but when I ran it I got this error "
Field entityManager in sagala.rest.boot.remade.dao.EmployeeDaoImpl required a bean of type 'javax.persistence.EntityManager' that could not be found.".
Here is my controller class
package sagala.rest.boot.remade.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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sagala.rest.boot.remade.entity.Employee;
import sagala.rest.boot.remade.service.EmployeeService;
#RestController
#RequestMapping("/api")
public class MainController {
#Autowired
private EmployeeService employeeService;
#GetMapping("/employees")
public List<Employee> findAll() {
return employeeService.findAll();
}
}
Here is the Service class
package sagala.rest.boot.remade.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sagala.rest.boot.remade.dao.EmployeeDao;
import sagala.rest.boot.remade.entity.Employee;
#Service
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
private EmployeeDao employeeDao;
#Override
#Transactional
public List<Employee> findAll() {
return employeeDao.findAll();
}
}
Here is the DAO class
package sagala.rest.boot.remade.dao;
import java.util.List;
import javax.persistence.EntityManager;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import sagala.rest.boot.remade.entity.Employee;
#Repository
public class EmployeeDaoImpl implements EmployeeDao {
#Autowired
private EntityManager entityManager;
#Override
public List<Employee> findAll() {
Session session =entityManager.unwrap(Session.class);
Query<Employee> query =session.createQuery("from Employee", Employee.class);
List<Employee> employees =query.getResultList();
return employees;
}
}
Here is the entity class
package sagala.rest.boot.remade.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
public Employee() {
}
public Employee(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Here is the POM file
<?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.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>sagala</groupId>
<artifactId>rest.boot.remade</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rest.boot.remade</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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>
Here is the application properties
spring.datasource.url=jdbc:mysql://localhost:3306/employee_directory?useSSL=false&serverTimezone=UTC
spring.datasource.username=spring*******
spring.datasource.password=spring*******
If anyone can help me. Thanks
I changed the spring boot version from 2.2.6 to 2.1.13 and everything works fine. Seems like the javax.persistence.EntityManager is corrupt in the newer spring boot version. Eventhough deleted repo multiple times, I still could not find JpaRepository interface when try to extends it as another alternative dao implementation.

MapStruct ignores fields

I'm new to Java Spring Boot. I decided to use MapStruct because it's similar to ASP.NET Core's AutoMapper.
Problem:
The image is pretty self explanatory. It doesn't map firstName and lastName. I thought it could be the underscore e.g. first_name, but then I added password to the DTO model and it's not being set too.
By the way, I tested it by removing the DTO model with the following code and it worked which means that the cause is that UserMapper.
#GetMapping
public ResponseEntity<List<User>> getAll() {
return ResponseEntity.ok(userService.getAll());
}
Log from ReportingPolicy.WARN
2019-10-27 15:58:44.024 DEBUG 24284 --- [nio-5000-exec-1] org.hibernate.SQL : select user0_.id as id1_2_, user0_.email as email2_2_, user0_.first_name as first_na3_2_, user0_.last_name as last_nam4_2_, user0_.password as password5_2_ from users user0_
2019-10-27 15:58:44.033 DEBUG 24284 --- [nio-5000-exec-1] org.hibernate.SQL : select roles0_.user_id as user_id1_1_0_, roles0_.role_id as role_id2_1_0_, role1_.id as id1_0_1_, role1_.description as descr
UserMapper.java
package com.holding.server.mappers;
import java.util.List;
import com.holding.server.dto.UserDTO;
import com.holding.server.entities.User;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
#Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.WARN)
public interface UserMapper {
UserDTO toUserDTO(User user);
List<UserDTO> toUserDTOs(List<User> users);
User toUser(UserDTO userDTO);
}
User.java
package com.holding.server.entities;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Entity(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique = true)
#NotNull
#Size(max = 40)
#Email
private String email;
#NotNull
private String password;
#NotNull
#Size(max = 40)
private String firstName;
#NotNull
#Size(max = 40)
private String lastName;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles;
}
UserDTO.java
package com.holding.server.dto;
import lombok.Data;
#Data
public class UserDTO {
private String email;
private String firstName;
private String lastName;
}
UserServiceImpl.java
package com.holding.server.services;
import java.util.List;
import java.util.Optional;
import com.holding.server.entities.User;
import com.holding.server.repositories.UserRepository;
import com.holding.server.services.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import lombok.AllArgsConstructor;
#AllArgsConstructor
#Service
public class UserServiceImpl implements UserService {
private UserRepository userRepository;
private BCryptPasswordEncoder bCryptPasswordEncoder;
#Override
public List<User> getAll() {
return userRepository.findAll();
}
#Override
public Optional<User> get(Long id) {
return userRepository.findById(id);
}
#Override
public Optional<User> create(User user) {
if (userRepository.findByEmail(user.getEmail()).isPresent()) {
return Optional.empty();
}
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
return Optional.ofNullable(userRepository.save(user));
}
#Override
public Optional<User> update(User user) {
Optional<User> userToUpdate = get(user.getId());
if (userToUpdate.isPresent()) {
userToUpdate.get().setFirstName(user.getFirstName());
userToUpdate.get().setLastName(user.getLastName());
userToUpdate.get().setRoles(user.getRoles());
if (user.getPassword() != null) {
userToUpdate.get().setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
}
return Optional.ofNullable(userRepository.save(userToUpdate.get()));
}
return Optional.empty();
}
#Override
public void delete(Long id) {
Optional<User> user = get(id);
if (user.isPresent()) {
userRepository.delete(user.get());
}
}
}
UserController.java
package com.holding.server.controllers;
import java.util.List;
import java.util.Optional;
import com.holding.server.dto.UserDTO;
import com.holding.server.entities.User;
import com.holding.server.mappers.UserMapper;
import com.holding.server.services.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;
import lombok.AllArgsConstructor;
#AllArgsConstructor
#RestController
#RequestMapping("/api/users")
public class UserController {
private UserService userService;
private UserMapper userMapper;
#GetMapping
public ResponseEntity<List<UserDTO>> getAll() {
return ResponseEntity.ok(userMapper.toUserDTOs(userService.getAll()));
}
#GetMapping("/{id}")
public ResponseEntity<UserDTO> get(#PathVariable("id") Long id) {
Optional<User> user = userService.get(id);
if (user.isPresent()) {
return ResponseEntity.ok(userMapper.toUserDTO(user.get()));
}
return ResponseEntity.notFound().build();
}
#PostMapping
public ResponseEntity<UserDTO> create(#RequestBody UserDTO userDTO) {
User user = userMapper.toUser(userDTO);
user.setId(null);
Optional<User> savedUser = userService.create(user);
if (savedUser.isPresent()) {
return ResponseEntity.ok(userMapper.toUserDTO(savedUser.get()));
}
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
#PutMapping("/{id}")
public ResponseEntity<UserDTO> update(#PathVariable(required = true) Long id, #RequestBody UserDTO userDTO) {
User user = userMapper.toUser(userDTO);
user.setId(id);
Optional<User> updatedUser = userService.update(user);
if (updatedUser.isPresent()) {
return ResponseEntity.ok(userMapper.toUserDTO(updatedUser.get()));
}
return ResponseEntity.badRequest().build();
}
#DeleteMapping("/{id}")
public ResponseEntity<Void> delete(#PathVariable(required = true) Long id) {
if (userService.get(id).isPresent()) {
userService.delete(id);
return ResponseEntity.ok().build();
}
return ResponseEntity.notFound().build();
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<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.0.RELEASE</version>
<relativePath />
</parent>
<groupId>com.holding</groupId>
<artifactId>server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<org.mapstruct.version>1.3.1.Final</org.mapstruct.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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.10.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
If you need something else, ask me.
MapStruct creates generated class at compile time. You might want to clean and rebuild then check if the generated Mapper contains the required mappings.

Problem with a query in a Java Spring project using H2 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have a project that uses H2 as the database and I'm trying to make a query of all users on it on my UserDAO, but when I try to run the terminal gives me a lot of errors and doesn't start the server, but when I comment the line of the query the program runs normally.
ERROR
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController': Unsatisfied dependency expressed through field 'usuarioService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'usuarioService' defined in file [/home/gustavolbs/PSOFT/back-end/lab3/target/classes/com/lab2/crud/service/UsuarioService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAO': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Using named parameters for method public abstract com.lab2.crud.model.User com.lab2.crud.dao.UserDAO.findByLogin(java.lang.String) but parameter 'Optional[searchLogin]' not found in annotated query 'Select u from User u where u.login=:plogin'!
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.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lab2</groupId>
<artifactId>crud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>crud</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>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Login Controller
package com.lab2.crud.controller;
import java.util.Date;
import javax.servlet.ServletException;
import com.lab2.crud.model.User;
import com.lab2.crud.service.UsuarioService;
import org.springframework.beans.factory.annotation.Autowired;
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 io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
#RestController
#RequestMapping("/v1/auth")
public class LoginController {
private final String TOKEN_KEY = "banana";
#Autowired
private UsuarioService usuarioService;
#PostMapping("/login")
public LoginResponse authenticate(#RequestBody User usuario) throws ServletException {
// Recupera o usuario
User authUsuario = usuarioService.findByLogin(usuario.getLogin());
// verificacoes
if(authUsuario == null) {
throw new ServletException("Usuario nao encontrado!");
}
if(!authUsuario.getPassword().equals(usuario.getPassword())) {
throw new ServletException("Senha invalida!");
}
String token = Jwts.builder().
setSubject(authUsuario.getLogin()).
signWith(SignatureAlgorithm.HS512, TOKEN_KEY).
setExpiration(new Date(System.currentTimeMillis() + 1 * 60 * 1000))
.compact();
return new LoginResponse(token);
}
private class LoginResponse {
public String token;
public LoginResponse(String token) {
this.token = token;
}
}
}
UsuarioController
package com.lab2.crud.controller;
import com.lab2.crud.model.User;
import com.lab2.crud.service.UsuarioService;
import com.lab2.exception.Usuario.UsuarioJaExisteException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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;
#RestController
#RequestMapping("/v1/usuarios")
public class UsuarioController {
#Autowired
private UsuarioService usuarioService;
UsuarioController(UsuarioService usuarioService) {
this.usuarioService = usuarioService;
}
#PostMapping(value="/")
public ResponseEntity<User> create(#RequestBody User usuario) {
if (usuarioService.findByLogin(usuario.getLogin()) != null) {
throw new UsuarioJaExisteException("Usuário já existe");
}
User newUser = usuarioService.create(usuario);
if (newUser == null) {
throw new InternalError("Something went wrong");
}
return new ResponseEntity<User>(newUser, HttpStatus.CREATED);
}
}
When I comment the line of the query on the UserDAO the program runs, but it doesn't do the search for the login.
UserDAO
package com.lab2.crud.dao;
import java.io.Serializable;
import java.util.List;
import com.lab2.crud.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
#Repository
public interface UserDAO<T, ID extends Serializable> extends JpaRepository<User, String> {
User save(User usuario);
User findById(long id);
#Query("Select u from User u where u.login=:plogin")
User findByLogin(#Param("searchLogin") String login);
List<User> findAll();
}
UserModel #
package com.lab2.crud.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
#Data
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String login;
private String password;
public User() {
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public User(String name, String login, String password) {
this.name = name;
this.login = login;
this.password = password;
}
}
application.properties
server.port = 8080
# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2
#indicará o path para você acessar a interface do h2, em geral, vá ao browser e coloque localhost:8080/h2 com 8080 ou sua porta
# Datasource
spring.datasource.url=jdbc:h2:file:~/PSOFT/back-end/lab3/test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=update
server.servlet.context-path=/api
#diz ao spring que coloque /api antes de qualquer url, ou seja, se voce quiser utilizar as rotas /products, precisará adicionar /api => /api/v1/products e assim por diante
I've tried to rewrite the Query on another ways, tried re-import the package, run on another machine, but nothing works and I don't know what and why solve. Can anyone help me with this?
In the DAO
#Query("Select u from User u where u.login=:plogin")
User findByLogin(#Param("searchLogin") String login);
You have declared searchLogin as the parameter with #Param annotation but in the query you have used plogin as the parameter. Replace plogin with searchLogin in the query as shown below,
#Query("Select u from User u where u.login=:searchLogin")
User findByLogin(#Param("searchLogin") String login);

Resources