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

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

Related

The request resource is not available - Spring, Hibernate, mvn

If we look into the StudentController, request mapping is #RequestMapping("/rest") for class
and get mapping is #GetMapping("/test").
Hence for url http://localhost:8080/TestHibernate/rest/test, I should get a string 'success', which I am not getting.
On executing url http://localhost:8080/TestHibernate I am getting the content placed in index file.
Please let me know what part I am missing.
Thank you.
Controller class
package com.akshay.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.akshay.dao.StudentDAO;
import com.akshay.entity.Student;
#RestController
#RequestMapping("/rest")
public class StudentController {
#Autowired
private StudentDAO studentDAO;
#PostMapping("/saveStudent")
public String save(#RequestBody Student student) {
studentDAO.saveStudent(student);
return "Saved Successfully";
}
#GetMapping("/test")
public String test() {
return "Success";
}
}
DAO Layer
package com.akshay.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.akshay.entity.Student;
#Repository
#Transactional
public class StudentDAO {
#Autowired
private SessionFactory factory;
private Session getSession() {
Session session = factory.getCurrentSession();
if(session == null) {
session = factory.openSession();
}
return session;
}
public void saveStudent(Student student) {
getSession().save(student);
}
}
Entity Layer
package com.akshay.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 = "student")
public class Student {
#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 Student() {
}
public Student(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;
}
#Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
Entry Point
package com.akshay.TestHibernate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TestHibernateApplication {
public static void main(String[] args) {
SpringApplication.run(TestHibernateApplication.class, args);
}
}
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.5.0</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.akshay</groupId>
<artifactId>TestHibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>TestHibernate</name>
<description>Demo project to test hibernate and mysql</description>
<properties>
<java.version>11</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-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<!--<scope>provided</scope> -->
</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>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
#
# JDBC connection properties
#
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/web_student_tracker
jdbc.user=springstudent
jdbc.password=springstudent
#
# Connection pool properties
#
connection.pool.initialPoolSize=5
connection.pool.minPoolSize=5
connection.pool.maxPoolSize=20
connection.pool.maxIdleTime=3000
#
# Hibernate properties
#
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.packagesToScan=com.akshay.entity
Introduction
Let's consider the following versions as the current versions:
Spring Boot: 2.7.1.
Analysis
Please, note that the package of the controller class (com.akshay.controller.StudentController) is not the same as the package of the application class (com.akshay.TestHibernate.TestHibernateApplication).
Let's refer to the documentation: Developing with Spring Boot: 6. Using the #SpringBootApplication Annotation:
Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their "application class". A single #SpringBootApplication annotation can be used to enable those three features, that is:
#EnableAutoConfiguration: enable Spring Boot’s auto-configuration mechanism
#ComponentScan: enable #Component scan on the package where the application is located (see the best practices)
#SpringBootConfiguration: enable registration of extra beans in the context or the import of additional configuration classes. An alternative to Spring’s standard #Configuration that aids configuration detection in your integration tests.
Please, note:
#ComponentScan: enable #Component scan on the package where the application is located (see the best practices)
Solution
It is necessary to add the controller package to be component-scanned.
For example:
<…>
#SpringBootApplication
#ComponentScan(basePackages="com.akshay.controller")
public class TestHibernateApplication {
<…>
Test the controller method execution by performing an HTTP request:
curl -X GET http://localhost:8080/rest/test
Additional references
Stack Overflow question. java - Spring Boot: Cannot access REST Controller on localhost (404) - Stack Overflow.

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

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.

#RequestMapping not redirecting to the specified URL : Spring Boot application

I am trying to create a sample spring boot application which can connect to postgres. But I am not able to redirect to the path specified in the rest controller. The code for my project is given below:
pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.vmware.springboot</groupId>
<artifactId>SpringBootSample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBootDemo1</name>
<description>Sample project for Spring Eureka</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<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.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</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>
application.properties
server.port=3000
spring.datasource.url= jdbc:postgresql://localhost:5432/local_db
spring.datasource.data-username=postgres
spring.datasource.data-password=postgres
spring.jpa.hibernate.ddl-auto=create-drop
SpringBootExampleApplication.java
package org.kumar.springboot;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.kumar.spring.enitiy.Employee;
#SpringBootApplication
#ComponentScan
public class SpringBootExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootExampleApplication.class, args);
}
}
EmployeeController.java
package org.kumar.spring.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.RestController;
import org.kumar.spring.enitiy.Employee;
import org.kumar.spring.repository.EmployeeRepository;
#RestController
#RequestMapping("/data")
public class EmployeeController {
#Autowired
private EmployeeRepository employeeRepository;
#RequestMapping("/employees")
public List<Employee> getEmployees(){
return (List<Employee>)employeeRepository.findAll();
}
}
Employee.java
package org.kumar.spring.enitiy;
public class Employee {
private String employeeId;
private String employeeName;
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
#Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + "]";
}
public Employee(String employeeId, String employeeName) {
super();
this.employeeId = employeeId;
this.employeeName = employeeName;
}
}
EmployeeRepository.java
package org.kumar.spring.repository;
import org.springframework.data.repository.CrudRepository;
import org.kumar.spring.enitiy.Employee;
public interface EmployeeRepository extends CrudRepository<Employee, String>
{
}
I am trying to run the following:
Request : GET http://localhost:3000/data/employees
Response :
{
"timestamp": 1492152367659,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/data/employees"
}
What mistake am I committing.
Basically, your EmployeeController class has not been detected/scanned by the Spring container because of the classes are in different package hierarchy and the container has not been instructed to scan in which package to look for.
So there are two options to solve the issue:
(1) Change your SpringBootExampleApplication class package to org.kumar.spring
(2) Add #ComponentScan(basePackages = {"org.kumar.spring"})
I suggest you prefer the option(1) above otherwise, for option(2), you need to add #EnableJpaRepositories to make the program to work from end to end (i.e., connecting to the database using your EmployeeRepository class).

Resources