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

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!

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.

No qualifying bean of type,expected at least 1 bean which qualifies as autowire, org.springframework.beans.factory.UnsatisfiedDependencyException:

I Created a simple Springboot Application with H2 DB. Not able to start the spring boot Application getting below error on startup. I have added all the necessary configurations.
Exception encountered during context initialization - cancelling
refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'studentController': Unsatisfied
dependency expressed through field 'studentService'; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.example.test.serviceimpl.StudentServiceImpl' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Controller:
package com.example.test.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.example.test.serviceimpl.StudentServiceImpl;
import comm.example.test.model.Student;
#RestController
public class StudentController {
#Autowired(required=true)
private StudentServiceImpl studentService;
#GetMapping("/student")
private List<Student> getAllStudent() {
return studentService.getAllStudent();
}
#GetMapping("/student/{id}")
private Student getStudent(#PathVariable("id") Long id) {
return studentService.getStudentById(id);
}
}
Student Pojo class
package comm.example.test.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
#Getter
#Setter
#AllArgsConstructor
#Entity
#Table(name="student")
public class Student {
#Id
#Column
private Long id;
#Column
private String name;
#Column
private int age;
#Column
private String email;
}
StudentService Interface:
package com.example.test.service;
import java.util.List;
import comm.example.test.model.Student;
public interface StudentService {
List<Student> getAllStudent();
Student getStudentById(Long id);
}
StudentServiceImpl:
package com.example.test.serviceimpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.test.repository.serviceimpl.StudentRepositoryServiceImpl;
import com.example.test.service.StudentService;
import comm.example.test.model.Student;
public class StudentServiceImpl implements StudentService {
#Autowired
private StudentRepositoryServiceImpl serviceImpl;
#Override
public List<Student> getAllStudent() {
return serviceImpl.getAllStudent();
}
#Override
public Student getStudentById(Long id) {
return serviceImpl.getStudentById(id);
}
}
RepositoryService:
package com.example.test.repository.serviceimpl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.test.repository.StudentRepository;
import comm.example.test.model.Student;
#Service
public class StudentRepositoryServiceImpl {
#Autowired
private StudentRepository repo;
public List<Student> getAllStudent() {
List<Student> students = new ArrayList<Student>();
repo.findAll().forEach(student -> students.add(student));
return students;
}
public Student getStudentById(Long id) {
return repo.findById(id).get();
}
}
Repository:
package com.example.test.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import comm.example.test.model.Student;
#Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}
Your StudentServiceImpl needs a #Service annotation to be injected.

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

java.lang.IllegalArgumentException: Not a managed type: class while initiating repository bean

Hi I am trying to load some database values at start time of spring boot application. I have autowired service, and in service i have autowired Dao. Below is the error.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'validationExpressionService': Unsatisfied dependency expressed through field 'validationExpressionDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IValidationExpressionDao': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.ril.nfg.dao.bean.ValidationExpression
I have added #EnitityScan #EnableJPARepository
FYI, Primary key in the case in String, hope that is ok.
Entity
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* The Class ValidationExpression.
*/
package com.ril.nfg.dao.bean;
#Entity
#Table(name = "VALIDATION_EXPRESSION")
public class ValidationExpression implements Serializable {
private static final long serialVersionUID = 9096950800262493651L;
private String validationId;
private String expression;
private String createdBy;
private Date createdOn;
private String description;
private String responseCode;
#Id
#Column(name = "VALIDATION_ID", nullable = false, length = 100)
public String getValidationId() {
return validationId;
}
public void setValidationId(String validationId) {
this.validationId = validationId;
}
#Column(name = "EXPRESSION", nullable = false, length = 200)
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
//remaining getters and setters
}
Repository
package com.ril.nfg.dao.repos;
import com.ril.nfg.dao.bean.ValidationExpression;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* The Interface IValidationExpressionDao.
*/
#Repository
public interface IValidationExpressionDao extends JpaRepository<ValidationExpression, String> {
}
Service
import java.util.List;
#Service
public class ValidationExpressionService {
#Autowired
IValidationExpressionDao validationExpressionDao;
public List<ValidationExpression> getAll() {
return validationExpressionDao.findAll();
}
}
Class with #Autwired Service
public class CacheModuleParam implements ApplicationContextAware{
private static List<ValidationExpression> validationExpressionList = null;
#Autowired
ValidationExpressionService validationExpressionService;
#Override
public void setApplicationContext(final ApplicationContext appContext) throws BeansException {
validationExpressionList = validationExpressionService.getAll();
}
}
Application Class
#ComponentScan(basePackages = {"com.ril.nfg"})
#EnableWebMvc
#EnableAutoConfiguration
#SpringBootApplication//(exclude={DataSourceAutoConfiguration.class})
#EnableJpaRepositories(basePackages="com.ril.nfg.dao.repos",entityManagerFactoryRef="oracleEntityManagerFactory")
//#EntityScan(basePackages = "com.ril.nfg.dao.bean")
public class NFGApplication {
public static void main(String[] args) {
SpringApplication.run(NFGApplication.class, args);
}
}
All solutions on internet focuses on #EntityScan. Please help me understand what is wrong with this code. Thanks in advance
Why do you have all this configuration? Simply put our application in the package tree one level above all the other classes and you can go with a class like this:
#SpringBootApplication
public class NFGApplication {
public static void main(String[] args) {
SpringApplication.run(NFGApplication.class, args);
}
}
Packages:
com.ril.nfg <- here you put NFGApplication
And all other classes in subpackages of com.ril.nfg
And then everything will work!

Spring 4 + Hibernate 4: ClassCastException with LocalSessionFactoryBean and SessionFactory

By mean of Spring libraries I have to develope a DAL (Data Access Layer) in the form of a jar library which will be imported into the main application.
I want to use Hibernate to access a MySQL DB and DBCP for the management of the connections pool.
I have written the config file DALConfig.java which contains the configuration of the DAL beans:
package my.dal.config;
import java.util.Properties;
import javax.annotation.Resource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
// Needed by Spring to add this class to the ApplicationContext's configuration
#Configuration
#ComponentScan(basePackages = { "my.dal.config" })
// Property file in which are written the MySQL connection properties
#PropertySource("classpath:dbconnection.properties")
public class DALConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_POOL_INITIAL_SIZE = "pool.initialsize";
private static final String PROPERTY_NAME_POOL_MAX_IDLE = "pool.maxidle";
// Needed to access property file
#Resource
private Environment environment;
// The bean which defines the BasicDataSource (DBCP)
#Bean
public BasicDataSource dataSource() throws Exception
{
Properties props = new Properties();
props.put("driverClassName", environment.getProperty(PROPERTY_NAME_DATABASE_DRIVER));
props.put("url", environment.getProperty(PROPERTY_NAME_DATABASE_URL));
props.put("username", environment.getProperty(PROPERTY_NAME_DATABASE_USERNAME));
props.put("password", environment.getProperty(PROPERTY_NAME_DATABASE_PASSWORD));
props.put("initialSize", environment.getProperty(PROPERTY_NAME_POOL_INITIAL_SIZE));
props.put("maxIdle", environment.getProperty(PROPERTY_NAME_POOL_MAX_IDLE));
BasicDataSource bds = BasicDataSourceFactory.createDataSource(props);
return bds;
}
// Bean used to translate Hibernate's exceptions into Spring's ones
#Bean
public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor()
{
PersistenceExceptionTranslationPostProcessor b = new PersistenceExceptionTranslationPostProcessor();
return b;
}
}
Then I wrote the HibernateConfig.java config file which contains the Hibernate configuration stuff
package my.dal.hibernateconfig;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
#Configuration
#ComponentScan(basePackages = { "my.dal.hibernatesessionfactory" })
#PropertySource("classpath:dbconnection.properties")
public class HibernateConfig {
private static final String PROPERTY_NAME_DAL_CLASSES_PACKAGE = "hibernate.dal.package";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
#Resource
private Environment environment;
#Autowired
DataSource dataSource;
// Bean which defines the FactoryBean for the SessionBean
#Bean
public LocalSessionFactoryBean sessionFactory()
{
LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
lsfb.setPackagesToScan(PROPERTY_NAME_DAL_CLASSES_PACKAGE);
Properties hibernateProperties = new Properties();
hibernateProperties.put("dialect", PROPERTY_NAME_HIBERNATE_DIALECT);
lsfb.setHibernateProperties(hibernateProperties);
lsfb.setDataSource(dataSource);
return lsfb;
}
#Bean
public HibernateTransactionManager transactionManager()
{
// THE EXCEPTION IS THROWN AT THIS LINE
HibernateTransactionManager htm = new HibernateTransactionManager((SessionFactory) sessionFactory());
return htm;
}
}
Next I wrote the UserDAO.java class which is a DAO for the User class which models the DB's User table.
package my.dal.dao;
import my.models.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Component
#Repository
#Transactional
public class UserDAO
{
private SessionFactory sessionFactory;
#Autowired
public UserDAO(SessionFactory sessionFactory) {
this.sessionFactory=sessionFactory;
}
public int insert(User user) {
return (Integer) sessionFactory.getCurrentSession().save(user);
}
public User getByUsername(String username) {
return (User) sessionFactory.getCurrentSession().get(User.class, username);
}
public void update(User user) {
sessionFactory.getCurrentSession().merge(user); // .update(user);
}
public void delete(String username) {
User u = getByUsername(username);
sessionFactory.getCurrentSession().delete(u);
}
}
The mapping class User.java (generated using the Eclipse's Hibernate tools) is
package my.models;
public class User implements java.io.Serializable {
private String username;
private String idUserKeystone;
private String firstName;
private String lastName;
private String password;
private String email;
private String emailRef;
private String employer;
private boolean confirmed;
// Getters, setters and full constructor
}
Now I want to test the DAL. The testing class is DALTest.java
package my.dal.tests;
import static org.junit.Assert.assertTrue;
import my.dal.config.DALConfig;
import my.dal.dao.UserDAO;
import my.dal.hibernateconfig.HibernateConfig;
import my.models.User;
import org.hibernate.SessionFactory;
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;
#ContextConfiguration(classes = { DALConfig.class, HibernateConfig.class})
#RunWith(SpringJUnit4ClassRunner.class)
public class DALTest {
#Autowired
UserDAO userDAO;
#Test
public void testGetUser() {
User user = null;
// Let's see if the user "myuser" is into the database
user = userDAO.getByUsername("myuser");
assertTrue(null != user);
}
}
When I run the test it throws the following exceptions
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class my.dal.hibernateconfig.HibernateConfig: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.hibernate4.HibernateTransactionManager my.dal.hibernateconfig.HibernateConfig.transactionManager()] threw exception; nested exception is java.lang.ClassCastException: org.springframework.orm.hibernate4.LocalSessionFactoryBean$$EnhancerBySpringCGLIB$$d866ed45 cannot be cast to org.hibernate.SessionFactory
...
Caused by: java.lang.ClassCastException: org.springframework.orm.hibernate4.LocalSessionFactoryBean$$EnhancerBySpringCGLIB$$d866ed45 cannot be cast to org.hibernate.SessionFactory
at my.dal.hibernateconfig.HibernateConfig.transactionManager(HibernateConfig.java:55)
at my.dal.hibernateconfig.HibernateConfig$$EnhancerBySpringCGLIB$$bd53a036.CGLIB$transactionManager$1(<generated>)
at my.dal.hibernateconfig.HibernateConfig$$EnhancerBySpringCGLIB$$bd53a036$$FastClassBySpringCGLIB$$119f2c5b.invoke(<generated>)
...
It seems like the problem is the cast at the line
HibernateTransactionManager htm = new HibernateTransactionManager((SessionFactory) sessionFactory())
On the contrary, the Internet is full of example writing that line that way.
What could be the problem?
Thank you in advance
A FactoryBean<Foo> is a bean that creates objects of type Foo. It's not, itself, of type Foo (as the javadoc would show you). To get the Foo it creates, you simply call getObject() on the factory bean:
HibernateTransactionManager htm =
new HibernateTransactionManager(sessionFactory().getObject());

Resources