Spring Boot java.lang.IllegalArgumentException: Not a managed type - spring

I'm trying to run a very simple Spring Boot application, but I get the following error messages:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'todoController': Unsatisfied dependency expressed through field 'todoDAO'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'todoDAO': Unsatisfied dependency expressed through field 'todoRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'todoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.ecominer.model.Todo
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'todoDAO': Unsatisfied dependency expressed through field 'todoRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'todoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.ecominer.model.Todo
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'todoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.ecominer.model.Todo
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.ecominer.model.Todo
Here is my main application class code:
package com.ecominer.network;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories("com.ecominer.repository")
#EnableJpaAuditing
#ComponentScan({"com.ecominer.controller", "com.ecominer.dao", "com.ecominer.model"})
public class NetworkApplication {
public static void main(String[] args) {
SpringApplication.run(NetworkApplication.class, args);
}
}
and here is the Todo class:
package com.ecominer.model;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
#Entity
#Table(name="todos")
#EntityListeners(AuditingEntityListener.class)
public class Todo {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
protected Todo() {}
private String label;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
I tried to add the corresponding package name to my #ComponentScan annotation and I tried adding the #Component annotation to my Todo class, none of which worked.

Try to configure #EntityScan to the main class NetworkApplication
#EntityScan(basePackages = "com.ecominer.model")
public class NetworkApplication {
...
}

Related

Spring Boot issue in join table query in my repository code

Getting unsatisfied dependency error while using #Query in Spring Boot
In my repository I have added query to join tables but getting error at runtime
ERROR:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empcontroller': Unsatisfied dependency expressed through field 'emprepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository' defined in com.emp.employeeMangement.api.Repository.EmployeeRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.emp.employeeMangement.api.Repository.EmployeeRepository.getJoinInformation(); Reason: Validation failed for query for method public abstract java.util.List com.emp.employeeMangement.api.Repository.EmployeeRepository.getJoinInformation()!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.emp.employeeMangement.api.Repository.EmployeeRepository.getJoinInformation()!
My code:
package com.emp.employeeMangement.api.Repository;
import com.emp.employeeMangement.api.DTO.ResponseDTO;
import com.emp.employeeMangement.api.Model.Employee;
import org.springframework.context.annotation.Bean;
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;
import java.util.List;
#Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long> {
#Query(value = "SELECT new com.emp.employeeMangement.api.DTO.ResponseDTO(e.empName,e.gender,e.email,e.empCode,a.noOfPresent,a.noOfAbsent) from Employee e JOIN e.Attendence a")
public List<ResponseDTO> getJoinInformation();
}
My controller code:
package com.emp.employeeMangement.api.Controller;
import com.emp.employeeMangement.api.DTO.RequestDTO;
import com.emp.employeeMangement.api.DTO.ResponseDTO;
import com.emp.employeeMangement.api.Exception.ResourceNotFoundException;
import com.emp.employeeMangement.api.Model.Employee;
import com.emp.employeeMangement.api.Repository.AttendenceRepository;
import com.emp.employeeMangement.api.Repository.EmployeeRepository;
import com.emp.employeeMangement.api.Repository.SalaryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class Empcontroller {
#Autowired
private EmployeeRepository emprepo;
#Autowired
private AttendenceRepository attrepo;
#Autowired
private SalaryRepository salRepo;
#PostMapping("/saveEmployee")
public Employee saveEmployee(#RequestBody RequestDTO dto){
return emprepo.save(dto.getEmployee());
}
#GetMapping("/findAllEmp")
public List<Employee> findAllEmp(){
return emprepo.findAll();
}
#GetMapping("/getInfo")
public List<ResponseDTO> getJoinInformation(){
return emprepo.getJoinInformation();
}
My response to:
package com.emp.employeeMangement.api.DTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class ResponseDTO {
private String empName;
private String email;
private String gender;
private int empCode;
private int noOfPresent;
private int noOfAbsent;
private int salAmount;
}
Spring Data tells you that the query is invalid. After a quick look it seems you are missing the field salAmount in the constructor.

Error in running sample Spring annotation based program without any xml

Hi I am trying to run a simple spring annotation based program without using any xml based configuration. I'm getting the error "Unsatisfied dependency expressed through field".
I learnt that using #ComponentScan spring scans the package mentioned and look for beans annotated.
Putting the code herein. My project is a maven project with hierarchy like MyProject/src/java/SpringAnnotnDemo/autowireAnnotationBased
There are three classed
Department.java
Employee.java
MainClass.java --> The main class
Department.java
package SpringAnnotnDemo.autowireAnnotationBased;
import org.springframework.stereotype.Component;
#Component
public class Department {
private String department;
public String getDeptName() {
return department;
}
public void setDeptName(String deptName) {
this.department = deptName;
}
}
Employee.java
package SpringAnnotnDemo.autowireAnnotationBased;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class Employee {
private int eid;
private String ename;
#Autowired
private Department department;
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public void showEployeeDetails() {
System.out.println("Employee Id : " + eid);
System.out.println("Employee Name : " + ename);
department.setDeptName("Mechanical Engineering");
System.out.println("Department : " + department.getDeptName());
}
}
MainClass.java
package SpringAnnotnDemo.autowireAnnotationBased;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan("SpringAnnotnDemo.autowireAnnotationBased")
public class MainClass {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(Employee.class);
Employee emp = ctx.getBean(Employee.class);
emp.setEid(374);
emp.setEname("S.C.B");
emp.showEployeeDetails();
}
}
On running this simple program I am getting an error as below.
`Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employee': Unsatisfied dependency expressed through field 'department'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'SpringAnnotnDemo.autowireAnnotationBased.Department' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}`
Can anyone please help me figure out what am I missing. I want the most simplest form of using annotation based spring without using any xml based configuration.
Change your this line
ApplicationContext ctx = new AnnotationConfigApplicationContext(Employee.class);
to this line
ApplicationContext ctx = new AnnotationConfigApplicationContext(MainClass.class);

Unsatisfied dependency expressed through field - Springboot the Application, the component and the test class are all in the same package

My understanding is that the SpringBootApplication annotation includes
ComponentScan
https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html
The bean is discovered and printed in Application.main(), why does the unit test not find it?
This unit test fails with:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.pds.pdssr.etlfile.EtlFileServicesTest': Unsatisfied dependency expressed through field 'etlFileServices'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pds.pdssr.etlfile.EtlFileServices' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
With the appropriate level of debug, i.e "org.springframework.context.annotation"="debug" I can see that the bean was discovered during component scanning.
Nevertheless, the unit test results in:
[ERROR] getAll(com.pds.pdssr.etlfile.EtlFileServicesTest) Time elapsed: 0.007 s <<< ERROR!
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.pds.pdssr.etlfile.EtlFileServicesTest': Unsatisfied dependency expressed through field 'etlFileServices'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pds.pdssr.etlfile.EtlFileServices' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pds.pdssr.etlfile.EtlFileServices' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
The Application:
package com.pds.pdssr.bootstrap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
//#EnableJpaRepositories("com.pds.pdsssr.jpa")
#SpringBootApplication
// #EntityScan("com.pds.pdssr.models")
public class Application {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(Application.class, args);
for (String name : applicationContext.getBeanDefinitionNames()) {
logger.info("bean: " + name);
}
}
}
The Component:
package com.pds.pdssr.bootstrap;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import javax.transaction.Transactional;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.pds.pdssr.models.EtlFile;
#Repository
public class EtlFileServices {
#Autowired
private static EntityManagerFactory entityManagerFactory;
public SessionFactory getSessionFactory() {
SessionFactory sessionFactory = null;
if (entityManagerFactory == null) {
throw new IllegalStateException("entityManagerFactory is null");
}
sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
if (sessionFactory == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return sessionFactory;
}
#SuppressWarnings("unchecked")
public List<EtlFile> getAll() {
return getAll("etlFile",getSessionFactory().getCurrentSession());
}
#SuppressWarnings("rawtypes")
protected List getAll(String tableName, Session session) {
String queryText = "from " + tableName;
return getList(tableName, queryText, session);
}
#SuppressWarnings("rawtypes")
protected List getList(String tableName, String queryText, Session session) {
long start = System.nanoTime();
Query query = session.createQuery(queryText);
List result = query.list();
long end = System.nanoTime();
long millis = (end - start) / 1000000;
//logger.debug("table: " + tableName + " millis " + millis + " rows: " + result.size());
return result;
}
}
The test class:
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringRunner;
import com.pds.pdssr.bootstrap.EtlFileServices;
import com.pds.pdssr.models.EtlFile;
#RunWith(SpringRunner.class)
public class EtlFileServicesTest {
#Autowired
private EtlFileServices etlFileServices;
#Test
public void getAll() {
List<EtlFile> etlFiles = etlFileServices.getAll();
assertNotNull(etlFiles);
}
}
Original answer:
You need to have
#RunWith(SpringRunner.class)
#SpringBootTest(classes = YourMainClass.class)
in your test class(es).
Further answer based on comment
If you really want to have SessionFactory in your project, you need to tell spring framework to have SessionContext explicitly. It can be done by add
spring.jpa.properties.hibernate.current_session_context_class = org.springframework.orm.hibernate5.SpringSessionContext
to your configuration file. Here's a working example for your problem.
HTH

error with project in spring, hibernate

This the error that I'm getting:
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usuarioControlador': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.blah.base.database.DAO.UsuarioDAO com.blah.base.controlador.UsuarioControlador.usuarioDAO; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'UsuarioDAO' defined in file [C:\Users\Owner\workspaceSpring.metadata.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\base\WEB-INF\classes\com\yavale\base\database\hibernetDAO\UsuarioHibernetDao.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.SessionFactory]: : No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier(value=sessionFactory)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier(value=sessionFactory)}
This is my UsuarioControlador (controller):
#Controller
#RequestMapping("/")
public class UsuarioControlador {
private UsuarioDAO usuarioDAO;
#Autowired
public void setUsuarioDAO(UsuarioDAO usuarioDAO) {
this.usuarioDAO = usuarioDAO;
}
#RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
List<Usuario> usuarios = usuarioDAO.listarUsuarios();
model.addAttribute("usuarios", usuarios);
return "index";
}
}
This is UsuarioDAO:
public interface UsuarioDAO {
void insertarUsuario(Usuario usuario);
void modificarUsuario(Usuario usuario);
List<Usuario> listarUsuarios();
Usuario buscarUsuario(String idUsuario);
void eliminarUsuario(Usuario usuario);
}
This is the class that implements UsuarioDAO:
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;
#Service(value="UsuarioDAO")
public class UsuarioHibernetDao extends HibernateDaoSupport implements UsuarioDAO{
#Autowired
public UsuarioHibernetDao(#Qualifier("mySessionFactory") SessionFactory
sessionFactory) {
this.setSessionFactory(sessionFactory);
}
public void insertarUsuario(Usuario usuario) {
this.getHibernateTemplate().save(usuario);
}
public void modificarUsuario(Usuario usuario) {
this.getHibernateTemplate().update(usuario);
}
public List<Usuario> listarUsuarios() {
return this.getHibernateTemplate().find("from Usuario");
}
public Usuario buscarUsuario(String idUsuario) {
return this.getHibernateTemplate().load(Usuario.class, idUsuario);
}
public void eliminarUsuario(Usuario usuario) {
this.getHibernateTemplate().delete(usuario);
}
}
This is my servlet-context.xml: https://dl.dropboxusercontent.com/u/31349296/servlet-context.xml
I'm new with spring so Im completely lost with this.
Edit: this is the complete stack trace: https://dl.dropboxusercontent.com/u/31349296/log.txt
Edit2:
You are using the wrong identifier in the Qualifier annotation. The bean id is "mySessionFactory" but you have given "sessionFactory". Also, make sure content component scan is scanning the right packages.
Update:
The other error is probably related to the import of the hibernate session. You should be using org.hibernate.Session instead of org.hibernate.classic.Session

Caused by: org.hibernate.MappingException: Could not determine type for: Employees [org.hibernate.mapping.Column(employees)]

I am using Hibernate 4.1.0.Final with Spring 3.1.1 .
When I am doing junit test, I am getting the following exception
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'sessionFactory' defined in class path resource [spring-
context.xml]: Invocation of init method failed; nested exception is
org.hibernate.MappingException: Could not determine type for:
test.entity.Employees,at table: PROJECT, for columns:
[org.hibernate.mapping.Column(employees)]
Project Entity class
#Entity
#Table(name = "PROJECT")
public class Project {
#OneToOne
#JoinColumn(name="EMP_NUMBER")
private Employees employees;
.....
Employee Entity class
#Entity
#Table(name = "EMPLOYEES")
public class Employees {
private String employeeNo;
#Id
#Column(name = "EMP_NUMBER")
public String getEmployeeNo() {
return employeeNo;
}
public void setEmployeeNo(String employeeNo) {
this.employeeNo = employeeNo;
}
Junit
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations="classpath:spring-context.xml")
#TransactionConfiguration(defaultRollback=true,transactionManager="transactionManager")
public class ProjectTest {
#Autowired
private ProjectDAO projectDAO;
#Test
public void testProjectId() {
Project project = projectDAO.findProjectId(1L);
assertNotNull(project);
}
}
This blog might help you to set up unidirectional #OneToOne association!

Resources