JpaRepsitory giving error while using method existsByUserName(String userName); - spring

I have created a JpaRepository interface where i define a method named existsByUserName(String userName). But because of this method, i am getting error.
UserRepository interface
package org.avijit.DAO; import org.avijit.Domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User, Integer> {
boolean existsByUserName(String userName);
}
My Controller class is
package org.avijit.Controller;
import org.avijit.DAO.UserRepository;
import org.avijit.Domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.validation.Valid;
import java.util.List;
#Controller
public class baseController {
#Autowired
UserRepository userRepository;
#RequestMapping("/")
public String homePage() {
System.out.println(userRepository.findAll());
return "HomePage";
}
#RequestMapping("/register")
public String register(Model model) {
model.addAttribute(new User());
return "RegistrationPage";
}
#RequestMapping(value = "/doRegistration", method = RequestMethod.POST)
public String doRegistration(#Valid #ModelAttribute("user") User user, BindingResult result) {
if (result.hasErrors()) {
return "RegistrationPage";
} else {
if (user.getId() < 0) {
userRepository.save(user);
return "redirect:/memberList";
} else {
User tempUser = userRepository.findOne(user.getId());
if (!tempUser.getUserName().equals(user.getUserName()) && userRepository.existsByUserName(user.getUserName())) {
result.rejectValue("userName", "DuplicateKey.user.userName", "This username already exist! Try again !");
return "RegistrationPage";
} else {
tempUser.setFirstName(user.getFirstName());
tempUser.setLastName(user.getLastName());
tempUser.setUserName(user.getUserName());
tempUser.setMobile(user.getMobile());
tempUser.setAddress(user.getAddress());
tempUser.setPassword(user.getPassword());
userRepository.save(tempUser);
return "redirect:/memberList";
}
}
}
}
#RequestMapping(value = "/memberList")
public String memberList(Model model) {
List<User> list = userRepository.findAll();
model.addAttribute("list", list);
return "UserList";
}
}
My Entity class is
package org.avijit.Domain;
import org.hibernate.validator.constraints.NotBlank;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class User {
#Id
#GeneratedValue
private Integer id;
#NotBlank
private String firstName;
#NotBlank
private String lastName;
#NotBlank
private String userName;
#NotBlank
private String mobile;
#NotBlank
private String address;
#NotBlank
private String password;
public User() {
}
public User(String firstName, String lastName, String userName, String mobile, String address, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.userName = userName;
this.mobile = mobile;
this.address = address;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer 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 getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", userName='" + userName + '\'' +
", mobile='" + mobile + '\'' +
", address='" + address + '\'' +
", password='" + password + '\'' +
'}';
}
}
My pom.xml is
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>
<groupId>org.avijit.jpaproject</groupId>
<artifactId>jpaproject</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.4.Final</version>
</dependency>
<!--Extra Dependency -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
</dependencies>
And error stack trace is below
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'baseController': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property existsByUserName found for type User!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:592)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1702)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:482)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:431)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1468)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1309)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1401)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:361)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property existsByUserName found for type User!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1131)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:589)
... 60 more
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property existsByUserName found for type User!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241)
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:235)
at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:373)
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:353)
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:84)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:61)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:95)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:206)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:73)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:367)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:190)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:239)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:225)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)

Try Updating below line
#Repository public interface UserRepository extends JpaRepository {
with
#Repository public interface UserRepository extends JpaRepository<User,<data_type_primary_key>> {
replace "< data_type_primary_key>" with the actual data type of primary Key in your entity.

Just changed my jpa-version
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.9.RELEASE</version>
</dependency>
Now everything working fine !!!

As stated in this link
Currently to implements exists with predicate (e.g. existsByUsername)
we have to use #Query manually, e.g.
http://stackoverflow.com/a/27156094/122441
Please support this convenience method directly in Spring Data JPA.
So you have to write it manually with #Query
Please see the solution here
#Query("SELECT CASE WHEN COUNT(u) > 0 THEN 'true' ELSE 'false' END FROM ENTITY e WHERE e.username = :userName")
EDIT:
I got it working without query with dependency org.springframework.data:spring-data-jpa:jar:2.0.6.RELEASE

Related

Spring Error creating bean with name 'entityManagerFactory'

I am trying to create a custom method for all my repositories and am getting this error. Thank you for your help!
DailyData:
package com.test.demo.Entities;
import javax.persistence.*;
#Entity
#Table(name = "Daily_Data")
public class DailyData {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
#Column(name = "Day")
private int time;
#Column(name = "Average_Energy_Value")
private double dailyAvgEnergy_value;
#Column(name = "Maximum_Energy_Value")
private double dailyMaxEnergy_value;
#Column(name = "Minimum_Energy_Value")
private double dailyIdleEnergy_value;
#Column(name = "topics")
private String topics;
}
HourlyData:
package com.test.demo.Entities;
import javax.persistence.*;
#Entity
#Table(name = "HourlyData")
public class HourlyData {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
#Column(name = "Hour")
private int time;
#Column(name = "Average_Energy_Value")
private double hourlyAvgEnergy_value;
#Column(name = "Maximum_Energy_Value")
private double hourlyMaxEnergy_value;
#Column(name = "Idle_Energy_Value")
private double hourlyIdleEnergy_value;
#Column(name = "topics")
private String topics;
}
Weekly Data:
package com.test.demo.Entities;
import javax.persistence.*;
import java.sql.Timestamp;
#Entity
#Table(name = "Weekly_Data")
public class WeeklyData {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
#Column(name = "Week")
private int time;
#Column(name = "Average_Energy_Value")
private double weeklyAvgEnergy_value;
#Column(name = "Maximum")
private double weeklyMaxEnergy_value;
#Column(name = "Weekly_Data")
private double weeklyIdleEnergy_value;
#Column(name = "Weekly_Data")
private String topics;
}
RawData:
package com.test.demo.Entities;
import javax.persistence.*;
#Entity
#Table(name="Raw_Data")
public class RawData {
//same as in MqttDataModel
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
public Long id;
//TODO:mqttID?
//Same
#Column(name = "timestamp")
public double timestamp;
//Same
#Column(name = "energy_value")
public double energy_value;
//Same
#Column(name="topics")
public String topics;
public String getTopics() {
return topics;
}
public void setTopics(String topics) {
this.topics = topics;
}
public double getEnergy_value() {
return energy_value;
}
public void setEnergy_value(double energy_value) {
this.energy_value = energy_value;
}
public double getTimestamp() {
return timestamp;
}
public void setTimestamp(double timestamp) {
this.timestamp = timestamp;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Generic Repository:
package com.test.demo.GenericRepo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import java.io.Serializable;
import java.util.List;
#NoRepositoryBean
public interface GenericRepository<T,Long extends Serializable> extends JpaRepository<T, Long> {
public List<T> findFromToTimestamp(T t, double beginTime, double endTime);
public List<T> findByTime(T t, double time);
public List<T> findByTopics(T t, List<String> topics);
}
GenericRepositoryImpl:
package com.test.demo.GenericRepo;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.List;
public class GenericRepositoryImpl<T, Long extends Serializable>
extends SimpleJpaRepository<T, Long> implements GenericRepository<T, Long> {
private EntityManager entityManager;
public GenericRepositoryImpl(Class<T> domainClass, EntityManager em) {
super(domainClass, em);
}
#SuppressWarnings("unchecked")
#Transactional
#Override
public List<T> findFromToTimestamp(T t, double beginTime, double endTime) {
return entityManager.createQuery("SELECT * FROM :t WHERE timestamp BETWEEN :begin AND :end").setParameter("t", t.getClass()).setParameter("begin", beginTime).setParameter("end", endTime).getResultList();
}
#SuppressWarnings("unchecked")
#Transactional
#Override
public List<T> findByTime(T t, double time) {
return entityManager.createQuery("SELECT * FROM :t WHERE timestamp like :v").setParameter("t", t.getClass()).setParameter("v", time).getResultList();
}
#SuppressWarnings("unchecked")
#Transactional
#Override
public List<T> findByTopics(T t, List<String> topics) {
return entityManager.createQuery("SELECT * FROM :t WHERE topics like :v").setParameter("t", t.getClass()).setParameter("v", topics.toString()).getResultList();
}
}
RawDataRepository:
package com.test.demo.Repositories;
import com.test.demo.Entities.RawData;
import com.test.demo.GenericRepo.GenericRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface RawDataRepository extends GenericRepository<RawData, Long> {
}
Other repositories and services look the same
DailyDataService:
package com.test.demo.Services;
import com.test.demo.Repositories.DailyDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class DailyDataService {
DailyDataRepository dailyDataRepository;
}
Application:
package com.test.demo;
import com.test.demo.GenericRepo.GenericRepositoryImpl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories(basePackages = "com.test.demo.Repositories",
repositoryBaseClass = GenericRepositoryImpl.class)
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>testdb2</name>
<description>demo</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220924</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.5.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.5.Final</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Error
log:org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:874) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1344) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:330) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:113) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:693) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:510) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:374) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:134) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1707) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1452) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:936) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.23.jar:5.3.23] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.23.jar:5.3.23] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.5.jar:2.7.5] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.5.jar:2.7.5] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.5.jar:2.7.5] at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.5.jar:2.7.5] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.5.jar:2.7.5] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.5.jar:2.7.5] at com.test.demo.TestApplication.main(TestApplication.java:16) ~[classes/:na]
I checked everything again and again, bit I am really not sure what is wrong.
I suspect that the issue is that you are mixing different versions of Spring Boot. Version 3.0.0 and 2.7.5, this leads to a strange mix of dependencies. Your dependency management also defeats te purpose of the parent, which manages all the versions for you. You should remove the version tag from the dependencies you are using.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>testdb2</name>
<description>demo</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220924</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
This cleaned pom will use Spring Boot 2.7.5 dependencies (as declared in the parent). If you want to switch to 3.0.0 just change the version of your parent.
NOTE: When switching to Spring Boot 3.0.0 you need to use the JakartaEE classes (different packages) instead of the JavaEE packages.

How to resolve this org.springframework.beans.factory.UnsatisfiedDependencyException

I am trying to using Spring boot DATA JPA to connect with the MySQL database.In that, I was trying to create a custom query but ended up with this error. Can someone help me, please?
Here is the sample code:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'currencyExchangeController': Unsatisfied dependency expressed through field 'currencyExchage'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'currencyExchangeRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract com.example.easynotes.model.CurrencyExchangeServiceBean com.example.easynotes.repository.CurrencyExchangeRepository.findByFromAndTo(java.lang.String,java.lang.String)! No property from found for type CurrencyExchangeServiceBean!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:397) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1429) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at com.example.easynotes.EasyNotesApplication.main(EasyNotesApplication.java:14) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.2.1.RELEASE.jar:2.2.1.RELEASE]
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>
<groupId>com.example</groupId>
<artifactId>easy-notes</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>easy-notes</name>
<description>Rest API for a Simple Note Taking Application</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.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.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Java Code:
package com.example.easynotes.model;
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
#Entity
#EntityListeners(AuditingEntityListener.class)
#Table(name = "CurrencyExchange")
public class CurrencyExchangeServiceBean {
#Id
#GeneratedValue
private int conversionid;
private String fromCurrency;
private String toCurrency;
private BigDecimal coversionMultiple;
public CurrencyExchangeServiceBean(int conversionid, String fromCurrency, String toCurrency,
BigDecimal coversionMultiple) {
super();
this.conversionid = conversionid;
this.fromCurrency = fromCurrency;
this.toCurrency = toCurrency;
this.coversionMultiple = coversionMultiple;
}
public String getFromCurrency() {
return fromCurrency;
}
public void setFromCurrency(String fromCurrency) {
this.fromCurrency = fromCurrency;
}
public String getToCurrency() {
return toCurrency;
}
public void setToCurrency(String toCurrency) {
this.toCurrency = toCurrency;
}
public int getConversionid() {
return conversionid;
}
public void setConversionid(int conversionid) {
this.conversionid = conversionid;
}
public BigDecimal getCoversionMultiple() {
return coversionMultiple;
}
public void setCoversionMultiple(BigDecimal coversionMultiple) {
this.coversionMultiple = coversionMultiple;
}
public CurrencyExchangeServiceBean() {
}
#Override
public String toString() {
return "CurrencyExchangeServiceBean [conversionid=" + conversionid + ", fromCurrency=" + fromCurrency
+ ", toCurrency=" + toCurrency + ", coversionMultiple=" + coversionMultiple + "]";
}
}
package com.example.easynotes.controller;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.easynotes.exception.CurrencyExchangenotfound;
import com.example.easynotes.model.CurrencyExchangeServiceBean;
import com.example.easynotes.repository.CurrencyExchangeDao;
import com.example.easynotes.repository.CurrencyExchangeRepository;
#RestController
public class CurrencyExchangeController {
#Autowired
CurrencyExchangeRepository currencyExchage;
#Autowired
CurrencyExchangeDao currencyExchangeDao;
#GetMapping("/api/currencyExchange/{from}/to/{to}")
public CurrencyExchangeServiceBean getcurrencyExchange(#PathVariable String from, #PathVariable String to) {
CurrencyExchangeServiceBean c = currencyExchangeDao.gettheExchange(from, to);
if (c == null) {
throw new CurrencyExchangenotfound("no exchage found");
}
return c;
}
#PostMapping("/api/currencyExchange")
public void addcurrencytotheExchange(#RequestBody CurrencyExchangeServiceBean currencyExchangebean) {
currencyExchangeDao.addtotheExchange(currencyExchangebean);
}
}
package com.example.easynotes.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.easynotes.model.CurrencyExchangeServiceBean;
#Repository
public interface CurrencyExchangeRepository extends JpaRepository<CurrencyExchangeServiceBean, Integer> {
CurrencyExchangeServiceBean findByFromAndTo(String fromCurrency, String toCurrency);
}
package com.example.easynotes;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
#SpringBootApplication(scanBasePackages = { "com.example.*" })
#EnableJpaAuditing
public class EasyNotesApplication {
public static void main(String[] args) {
SpringApplication.run(EasyNotesApplication.class, args);
}
}
One of the best things in Spring is it's verbosity when it comes to errors.
Most of the time the errors will tell you exactly what's wrong. Like in your case.
The first line in your Stacktrace says:
(...) No property from found for type CurrencyExchangeServiceBean!
And this is exactly what I can see in the code of your CurrencyExchangeServiceBean:
private String fromCurrency;
In order to resolve your error you can now either:
a) rename the property from fromCurrency to from
b) rename the method in your Repository to findByFromCurrencyAndToCurrency
BTW. The exact same error will occur for the toCurrency vs to.

how to fix "UnsatisfiedDependencyException: Error creating bean with name .EurekaServerAutoConfiguration'"

we are using eclipse + spring suit tool to test spring boot config service project, the compile/package/test in IDE works well.
when we ship to server and startup the jar application, we got following errors:
org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is
org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:155)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:333)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1277)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1265)
at com.ctrip.framework.apollo.configservice.ConfigServiceApplication.main(ConfigServiceApplication.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:54)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:126)
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:86)
at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:413)
at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:174)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:179)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:152)
... 14 common frames omitted
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.cloud.netflix.eureka.server.EurekaServerAutoConfiguration': Unsatisfied dependency expressed through field 'eurekaServerConfig'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'eurekaServerConfig' defined in class path resource [org/springframework/cloud/netflix/eureka/server/EurekaServerAutoConfiguration$EurekaServerConfigBeanConfiguration.class]: Unsatisfied dependency expressed through method 'eurekaServerConfig' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'apolloEurekaClientConfig' defined in URL [jar:file:/home/apollo/configservice-1.3.0/apollo-configservice.jar!/lib/apollo-biz-1.3.0.jar!/com/ctrip/framework/apollo/biz/eureka/ApolloEurekaClientConfig.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bizConfig': Invocation of init method failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1247)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1096)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:226)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:214)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addServletContextInitializerBeans(ServletContextInitializerBeans.java:91)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.<init>(ServletContextInitializerBeans.java:80)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getServletContextInitializerBeans(ServletWebServerApplicationContext.java:250)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.selfInitialize(ServletWebServerApplicationContext.java:237)
at org.springframework.boot.web.embedded.tomcat.TomcatStarter.onStartup(TomcatStarter.java:54)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5245)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1420)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1410)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
... 1 common frames omitted
here is our 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 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo</artifactId>
<version>1.3.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>apollo-configservice</artifactId>
<name>Apollo ConfigService</name>
<properties>
<github.path>${project.artifactId}</github.path>
</properties>
<dependencies>
<!-- apollo -->
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-biz</artifactId>
</dependency>
<!-- end of apollo -->
<!-- eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-cloud-starter-netflix-archaius</artifactId>
<groupId>org.springframework.cloud</groupId>
</exclusion>
<exclusion>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<groupId>org.springframework.cloud</groupId>
</exclusion>
<exclusion>
<artifactId>ribbon-eureka</artifactId>
<groupId>com.netflix.ribbon</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-core</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-ec2</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-autoscaling</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-sts</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-route53</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<!-- duplicated with spring-security-core -->
<exclusion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- end of eureka -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.4.13</version>
<configuration>
<imageName>${project.artifactId}</imageName>
<dockerDirectory>src/main/docker</dockerDirectory>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>*.zip</include>
</resource>
</resources>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>${project.artifactId}-${project.version}-${package.environment}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/assembly-descriptor.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
it's first time to touch spring appications, based on error log looks like the dependency for eureka, but don't know which jar dependency we should add. please give some hints for this problem. thanks a lot!!
the bizconfig class definition:
package com.ctrip.framework.apollo.biz.config;
import com.ctrip.framework.apollo.biz.service.BizDBPropertySource; import
com.ctrip.framework.apollo.common.config.RefreshableConfig; import
com.ctrip.framework.apollo.common.config.RefreshablePropertySource;
import com.google.common.base.Strings; import
com.google.common.collect.Maps; import com.google.gson.Gson; import
com.google.gson.reflect.TypeToken; import
org.springframework.stereotype.Component;
import java.lang.reflect.Type; import java.util.Collections; import
java.util.List; import java.util.Map; import
java.util.concurrent.TimeUnit;
#Component public class BizConfig extends RefreshableConfig {
private static final int DEFAULT_ITEM_KEY_LENGTH = 128; private
static final int DEFAULT_ITEM_VALUE_LENGTH = 20000; private static
final int DEFAULT_APPNAMESPACE_CACHE_REBUILD_INTERVAL = 60; //60s
private static final int DEFAULT_GRAY_RELEASE_RULE_SCAN_INTERVAL =
60; //60s private static final int
DEFAULT_APPNAMESPACE_CACHE_SCAN_INTERVAL = 1; //1s private static
final int DEFAULT_RELEASE_MESSAGE_CACHE_SCAN_INTERVAL = 1; //1s
private static final int DEFAULT_RELEASE_MESSAGE_SCAN_INTERVAL_IN_MS
= 1000; //1000ms private static final int DEFAULT_RELEASE_MESSAGE_NOTIFICATION_BATCH = 100; private static
final int
DEFAULT_RELEASE_MESSAGE_NOTIFICATION_BATCH_INTERVAL_IN_MILLI =
100;//100ms
private Gson gson = new Gson(); private static final Type
namespaceValueLengthOverrideTypeReference =
new TypeToken<Map<Long, Integer>>() {
}.getType();
private final BizDBPropertySource propertySource;
public BizConfig(final BizDBPropertySource propertySource) {
this.propertySource = propertySource; }
#Override protected List<RefreshablePropertySource>
getRefreshablePropertySources() {
return Collections.singletonList(propertySource); }
public List<String> eurekaServiceUrls() {
String configuration = getValue("eureka.service.url", "");
if (Strings.isNullOrEmpty(configuration)) {
return Collections.emptyList();
}
return splitter.splitToList(configuration); }
public int grayReleaseRuleScanInterval() {
int interval = getIntProperty("apollo.gray-release-rule-scan.interval",
DEFAULT_GRAY_RELEASE_RULE_SCAN_INTERVAL);
return checkInt(interval, 1, Integer.MAX_VALUE, DEFAULT_GRAY_RELEASE_RULE_SCAN_INTERVAL); }
public int itemKeyLengthLimit() {
int limit = getIntProperty("item.key.length.limit", DEFAULT_ITEM_KEY_LENGTH);
return checkInt(limit, 5, Integer.MAX_VALUE, DEFAULT_ITEM_KEY_LENGTH); }
public int itemValueLengthLimit() {
int limit = getIntProperty("item.value.length.limit", DEFAULT_ITEM_VALUE_LENGTH);
return checkInt(limit, 5, Integer.MAX_VALUE, DEFAULT_ITEM_VALUE_LENGTH); }
public Map<Long, Integer> namespaceValueLengthLimitOverride() {
String namespaceValueLengthOverrideString = getValue("namespace.value.length.limit.override");
Map<Long, Integer> namespaceValueLengthOverride = Maps.newHashMap();
if (!Strings.isNullOrEmpty(namespaceValueLengthOverrideString)) {
namespaceValueLengthOverride =
gson.fromJson(namespaceValueLengthOverrideString, namespaceValueLengthOverrideTypeReference);
}
return namespaceValueLengthOverride; }
public boolean isNamespaceLockSwitchOff() {
return !getBooleanProperty("namespace.lock.switch", false); }
/** * ctrip config **/ public String cloggingUrl() {
return getValue("clogging.server.url"); }
public String cloggingPort() {
return getValue("clogging.server.port"); }
public int appNamespaceCacheScanInterval() {
int interval = getIntProperty("apollo.app-namespace-cache-scan.interval",
DEFAULT_APPNAMESPACE_CACHE_SCAN_INTERVAL);
return checkInt(interval, 1, Integer.MAX_VALUE, DEFAULT_APPNAMESPACE_CACHE_SCAN_INTERVAL); }
public TimeUnit appNamespaceCacheScanIntervalTimeUnit() {
return TimeUnit.SECONDS; }
public int appNamespaceCacheRebuildInterval() {
int interval = getIntProperty("apollo.app-namespace-cache-rebuild.interval",
DEFAULT_APPNAMESPACE_CACHE_REBUILD_INTERVAL);
return checkInt(interval, 1, Integer.MAX_VALUE, DEFAULT_APPNAMESPACE_CACHE_REBUILD_INTERVAL); }
public TimeUnit appNamespaceCacheRebuildIntervalTimeUnit() {
return TimeUnit.SECONDS; }
public int releaseMessageCacheScanInterval() {
int interval = getIntProperty("apollo.release-message-cache-scan.interval",
DEFAULT_RELEASE_MESSAGE_CACHE_SCAN_INTERVAL);
return checkInt(interval, 1, Integer.MAX_VALUE, DEFAULT_RELEASE_MESSAGE_CACHE_SCAN_INTERVAL); }
public TimeUnit releaseMessageCacheScanIntervalTimeUnit() {
return TimeUnit.SECONDS; }
public int releaseMessageScanIntervalInMilli() {
int interval = getIntProperty("apollo.message-scan.interval", DEFAULT_RELEASE_MESSAGE_SCAN_INTERVAL_IN_MS);
return checkInt(interval, 100, Integer.MAX_VALUE, DEFAULT_RELEASE_MESSAGE_SCAN_INTERVAL_IN_MS); }
public int releaseMessageNotificationBatch() {
int batch = getIntProperty("apollo.release-message.notification.batch",
DEFAULT_RELEASE_MESSAGE_NOTIFICATION_BATCH);
return checkInt(batch, 1, Integer.MAX_VALUE, DEFAULT_RELEASE_MESSAGE_NOTIFICATION_BATCH); }
public int releaseMessageNotificationBatchIntervalInMilli() {
int interval = getIntProperty("apollo.release-message.notification.batch.interval",
DEFAULT_RELEASE_MESSAGE_NOTIFICATION_BATCH_INTERVAL_IN_MILLI);
return checkInt(interval, 10, Integer.MAX_VALUE, DEFAULT_RELEASE_MESSAGE_NOTIFICATION_BATCH_INTERVAL_IN_MILLI); }
public boolean isConfigServiceCacheEnabled() {
return getBooleanProperty("config-service.cache.enabled", false); }
int checkInt(int value, int min, int max, int defaultValue) {
if (value >= min && value <= max) {
return value;
}
return defaultValue; } }

Spring Data Repository Autowiring troubles

Im having trouble autowiring my CrudRespository in my Controller (I am using Spring boot).
Here are my Controller,Entity & Respository implementations
Repository:
package com.nbha.micro.ratingService;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
public interface RaterDORepository extends CrudRepository<RaterDO, Long> {
public RaterDO findByRaterName();
}
Entity:
#Entity
public class RaterDO {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long raterId;
public RaterDO(){}
public RaterDO(String n) {
this.raterName = n;
}
public Long getRaterId() {
return raterId;
}
public void setRaterId(Long raterId) {
this.raterId = raterId;
}
public String getRaterName() {
return raterName;
}
public void setRaterName(String raterName) {
this.raterName = raterName;
}
private String raterName;
}
Controller:
#RestController
#RequestMapping("/raters")
public class RaterController {
#Autowired
private RaterDORepository raterDORepository;
#RequestMapping("/add")
public String addRater(#RequestParam("name") String name) {
RaterDO raterDO = new RaterDO(name);
raterDORepository.save(raterDO);
return "Rater:" + name +" saved.";
}
#RequestMapping("/allRaters")
public String getAllRaters() {
StringBuilder sb = new StringBuilder();
sb.append("|");
Iterable<RaterDO> raters = raterDORepository.findAll();
for(RaterDO rater : raters) {
sb.append(rater.getRaterName());
sb.append("|");
}
return sb.toString();
}
}
Starter class:
#EnableBinding(ConsumerChannels.class)
#ComponentScan(basePackages={"com.nbha.micro.ratingService"})
#EntityScan(basePackages={"com.nbha.micro.ratingService"})
#EnableJpaRepositories(basePackages={"com.nbha.micro.ratingService"})
#SpringBootApplication
#EnableEurekaClient
#RestController
#RequestMapping("/ratings")
public class RatingApp
{
public static void main( String[] args )
{
System.out.println( "Invoking Rating Service.." );
SpringApplication.run(RatingApp.class, args);
}
#StreamListener(ConsumerChannels.PRODUCER)
public void receiveRater(final Rater rater) {
if(rater != null) {
System.out.println("Rating received in the rating-service:" + rater.getName());
}
}
private List<Rating> ratingList = Arrays.asList(
new Rating("R101","101",5),
new Rating("R102","102",2),
new Rating("R103","101",4),
new Rating("R104","101",1)
);
#GetMapping("/all")
public List<Rating> findAllRatings() {
return this.ratingList;
}
#GetMapping("/rating-agency")
public String whichRatingAgency() {
return "Moody's";
}
#GetMapping("")
public List<Rating> findRatingsByBookId(#RequestParam String bookId) {
Rating r;
List<Rating> rList = new ArrayList<Rating>();
ListIterator iter = this.ratingList.listIterator();
while(iter.hasNext()) {
r = (Rating)iter.next();
if(r.getBookId().equals(bookId)) {
rList.add(r);
}
}
return rList;
}
}
interface ConsumerChannels {
String PRODUCER = "producer";
#Input
SubscribableChannel producer();
}
I placed all these classes in the same package (in a desparate bid to make it work)
I keep getting the following error on application startup (fails to startup).The interesting thing is that a similar setup works in another instance without using #ComponentScan #EntityScan #EnableJpaRepository annotations :)
Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'raterController': Unsatisfied dependency expressed through field 'raterDORepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'raterDORepository': Invocation of init method failed; nested exception is java.util.NoSuchElementException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
....
Caused by: org.springframework.beans.factory.BeanCreationException:Error creating bean with name 'raterDORepository': Invocation of init method failed; nested exception is java.util.NoSuchElementException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans- 4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
....
Caused by: java.util.NoSuchElementException: null
at java.util.ArrayList$Itr.next(ArrayList.java:860) ~[na:1.8.0_151]
at org.springframework.data.jpa.repository.query.ParameterMetadataProvider.next(ParameterMetadataProvider.java:122) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryCreator$PredicateBuilder.build(JpaQueryCreator.java:302) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryCreator.toPredicate(JpaQueryCreator.java:208) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
....
Any clues will be appreciated. Here are my dependencies from pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies`enter code here`</artifactId>
<version>Brixton.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
public RaterDO findByRaterName(); needs a parameter, something like public RaterDO findByRaterName(String name).
Construction of the repository fails because the missing parameter prevents Spring Data to construct a proper method.

UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userDAO'

I am trying to connect backend and frontend two separate projects of eclipse spring maven. I have added dependency to do so. But when I write down validate credentials logic in Homecontroller.java, after running on server its showing this exception. Please help to resolve it I have tried many methods already please suggest.
HomeController.java
package com.yogesh.shoponlinefrontend.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.yogesh.shoponlineback.dao.UserDAO;
import com.yogesh.shoponlineback.model.User;
#Controller
public class HomeController {
#Autowired
UserDAO userDAO;
#RequestMapping("/")
public String homePage() {
System.out.println("Executing the method homePage");
return "home";
}
#RequestMapping("/login")
public ModelAndView showLoginPage() {
ModelAndView mv = new ModelAndView("home");
mv.addObject("msg", "You clicked login link");
mv.addObject("showLoginPage", "true");
return mv;
}
#RequestMapping("/register")
public ModelAndView showRegistrationPage() {
ModelAndView mv = new ModelAndView("home");
mv.addObject("msg", "You clicked Registration link ");
mv.addObject("showRegistrationPage", "true");
return mv;
}
#RequestMapping("/validate")
public ModelAndView validate(#RequestParam("id") String id, #RequestParam("password") String pwd) {
System.out.println("In validate method");
System.out.println("id: " + id);
System.out.println("pwd: " + pwd);
ModelAndView mv = new ModelAndView("home");
if (userDAO.validate(id, pwd) != null) {
mv.addObject("successMsg", "You logged in successfully");
} else {
mv.addObject("errorMsg", "Invalid Credentials..Please try again");
}
return mv;
}
}
UserDAO.java
package com.yogesh.shoponlineback.dao;
import java.util.List;
import com.yogesh.shoponlineback.model.User;
public interface UserDAO {
public List<User> list();
public User get(String username);
public User validate(String username, String password);
public boolean save(User user);
public boolean update(User user);
}
User.java
package com.yogesh.shoponlineback.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;
#Entity
//cha
#Table(name="USER")
#Component
public class User {
#Id
private String username;
#NotEmpty(message = "please enter your name")
private String name;
#Min(5)
#Max(15)
private String password;
private String mobile;
private String role;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
UserDAOImpl.java
package com.yogesh.shoponlineback.daoimpl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yogesh.shoponlineback.dao.UserDAO;
import com.yogesh.shoponlineback.model.User;
#Service
#Repository()
public class UserDAOImpl implements UserDAO {
#Autowired
UserDAO userDAO;
#Autowired
private SessionFactory sessionFactory;
public UserDAOImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public UserDAOImpl() {
// TODO Auto-generated constructor stub
}
#Transactional
public List<User> list() {
String hql = "from User";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}
#Transactional
public User get(String username) {
return (User) sessionFactory.getCurrentSession().get(User.class, username);
}
#Transactional
public User validate(String username, String password) {
String hql = "from User WHERE username ='" + username + "' and password='" + password + "'";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return (User)query.uniqueResult();
}
#Transactional
public boolean save(User user) {
try {
sessionFactory.getCurrentSession().save(user);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
#Transactional
public boolean update(User user) {
try {
sessionFactory.getCurrentSession().update(user);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
:::::::::::::::::::::::::::::Exception trace::::::::::::::::::::::::::::::::::
INFO: FrameworkServlet 'dispatcher': initialization started
Jan 10, 2017 3:19:22 PM **org.springframework.web.context.support.AnnotationConfigWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Tue Jan 10 15:19:22 IST 2017]; root of context hierarchy
Jan 10, 2017 3:19:22 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext loadBeanDefinitions
INFO: Registering annotated classes: [class com.yogesh.shoponlinefrontend.config.AppConfig]
Jan 10, 2017 3:19:23 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Jan 10, 2017 3:19:23 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userDAO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.yogesh.shoponlineback.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Jan 10, 2017 3:19:23 PM org.springframework.web.servlet.DispatcherServlet initServletBean
SEVERE: Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userDAO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.yogesh.shoponlineback.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:592)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370)
at `enter code here`org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754)
at** org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:992)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4903)
I have updated to this:
#ComponentScan(basePackages = "com.yogesh.shoponlinefrontend,com.yogesh.shoponlineback")
from
#ComponentScan(basePackages = "com.yogesh.shoponlinefrontend)
and it's now working fine.
I had the same problem! My POM file was configured incorrectly.
Check your dependencies (versions).
THis configuration works for me.
<?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>
<groupId>com.stoliarenko</groupId>
<artifactId>CustomerTracker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- <version>1.0-SNAPSHOT</version>-->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<packaging>war</packaging>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
<spring.version>5.1.0.RELEASE</spring.version>
<hibernate.version>5.3.5.Final</hibernate.version>
<hibernate.validator>5.4.1.Final</hibernate.validator>
<c3p0.version>0.9.5.2</c3p0.version>
<jstl.version>1.2.1</jstl.version>
<tld.version>1.1.2</tld.version>
<servlets.version>3.1.0</servlets.version>
<jsp.version>2.3.1</jsp.version>
<hsqldb.version>1.8.0.10</hsqldb.version>
</properties>
<dependencies>
<!-- Spring MVC Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.17.Final</version>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.validator}</version>
</dependency>
<!-- JSTL Dependency -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${tld.version}</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlets.version}</version>
<scope>provided</scope>
</dependency>
<!-- JSP Dependency -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</project>

Resources