Spring Boot issue in join table query in my repository code - spring

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.

Related

"UnsatisfiedDependencyException: Error creating bean with name ..." when running unit test on controller

So I have a controller class:
package microservices.book.multiplication.controller;
import microservices.book.multiplication.domain.MultiplicationResultAttempt;
import microservices.book.multiplication.repository.MultiplicationResultAttemptRepository;
import microservices.book.multiplication.service.MultiplicationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
#RestController("MultiplicationResultAttemptController")
#RequestMapping("/results")
final class MultiplicationResultAttemptController {
private static final Logger logger = LoggerFactory.getLogger(MultiplicationResultAttemptController.class);
private final MultiplicationService multiplicationService;
private final MultiplicationResultAttemptRepository attemptRepository;
#Autowired
public MultiplicationResultAttemptController(MultiplicationService multiplicationService,
MultiplicationResultAttemptRepository attemptRepository) {
this.multiplicationService = multiplicationService;
this.attemptRepository = attemptRepository;
}
}
And the relative test class is:
package microservices.book.multiplication.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import microservices.book.multiplication.domain.Multiplication;
import microservices.book.multiplication.domain.MultiplicationResultAttempt;
import microservices.book.multiplication.domain.User;
import microservices.book.multiplication.service.MultiplicationService;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.assertj.core.api.Assertions.assertThat;
#RunWith(SpringRunner.class)
#WebMvcTest(controllers = MultiplicationResultAttemptController.class)
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class MultiplicationResultAttemptControllerTest {
#MockBean
MultiplicationService multiplicationService;
#Autowired
private MockMvc mvc;
private JacksonTester<MultiplicationResultAttempt> jsonResult;
private JacksonTester<MultiplicationResultAttempt> jsonResponse;
private JacksonTester<List<MultiplicationResultAttempt>> jsonResultAttemptList;
#BeforeAll
void initAll(){
JacksonTester.initFields(this, new ObjectMapper());
}
#Test
public void postResultReturnCorrect() throws Exception{
genericParameterizedTest(true);
}
#Test
public void postResultReturnNotCorrect() throws Exception{
genericParameterizedTest(true);
}
void genericParameterizedTest(final Boolean correct) throws Exception{
given(multiplicationService.checkAttempt(any(MultiplicationResultAttempt.class))).willReturn(correct);
User user = new User("Smith");
Multiplication multiplication = new Multiplication(50,70);
MultiplicationResultAttempt attempt = new MultiplicationResultAttempt(user, multiplication, 3500, false);
// when
MockHttpServletResponse response = mvc.perform(
post("/results").contentType(MediaType.APPLICATION_JSON).
content(jsonResult.write(attempt).getJson())).
andReturn().getResponse();
// then
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(
jsonResponse.write(new MultiplicationResultAttempt(attempt.getUser(),
attempt.getMultiplication(),
attempt.getResultAttempt(),
correct)).getJson());
}
#Test
public void getUserStats() throws Exception {
// given
User user = new User("john_doe");
Multiplication multiplication = new Multiplication(50, 70);
MultiplicationResultAttempt attempt = new MultiplicationResultAttempt(user, multiplication, 3500,true);
List<MultiplicationResultAttempt> recentAttempts = Lists.newArrayList(attempt, attempt);
given(multiplicationService.getStatsForUsers("john_doe")).willReturn(recentAttempts);
// when
MockHttpServletResponse response = mvc.perform(
get("/results").param("alias", "john_doe")).andReturn().getResponse();
// then
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(jsonResultAttemptList.write(recentAttempts).getJson());
}
}
When I run this test class I get the error:
-------------------------------------------------------------------------------
Test set: microservices.book.multiplication.controller.MultiplicationResultAttemptControllerTest
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.715 s <<< FAILURE! - in microservices.book.multiplication.controller.MultiplicationResultAttemptControllerTest
microservices.book.multiplication.controller.MultiplicationResultAttemptControllerTest Time elapsed: 2.715 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'MultiplicationResultAttemptController' defined in file [C:\Users\pinguino\Desktop\Programming\social-multiplication\social-multiplication\target\classes\microservices\book\multiplication\controller\MultiplicationResultAttemptController.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'microservices.book.multiplication.repository.MultiplicationResultAttemptRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'microservices.book.multiplication.repository.MultiplicationResultAttemptRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Now, I can build the application with success.
The only line where the controller is mentioned in the test class is as parameter to the #WebMvcTest annotation. The repository which can't be found is this:
package microservices.book.multiplication.repository;
import microservices.book.multiplication.domain.MultiplicationResultAttempt;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface MultiplicationResultAttemptRepository extends CrudRepository<MultiplicationResultAttempt, Long> {
List<MultiplicationResultAttempt> findTop5ByUserAliasOrderByIdDesc(String userAlias);
}
I've also tried to add #Repository on the class but I get the same result.

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.

Encountered error "Consider defining a bean of type 'java.util.concurrent.atomic.AtomicReference' in your configuration"

I am getting the below error while starting spring boot application.
The injection point has the following annotations:
#org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type
'java.util.concurrent.atomic.AtomicReference' in your configuration.
Below is the code .
package de.summer.sampleapplayerv1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#SpringBootApplication(scanBasePackages = {"de.summer.sampleapplayerv1"})
#EnableConfigurationProperties
#EnableJpaRepositories (basePackages ="de.summer.sampleapplayerv1.repository")
#EnableTransactionManagement
public class Sampleapplayerv1Application {
public static void main(String[] args) {
SpringApplication.run(Sampleapplayerv1Application.class, args);
}
}
package de.summer.sampleapplayerv1.service;
import de.summer.sampleapplayerv1.domain.QueueAndPublish;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
#Slf4j
#Service
public class QueueAndPublishServiceImpl implements QueueAndPublishService{
private final AtomicReference<List<QueueAndPublish>> currentJob;
public QueueAndPublishServiceImpl(
#Qualifier("currentJob") AtomicReference<List<QueueAndPublish>> currentJob
){
this.currentJob=currentJob;
}
#Override
public QueueAndPublish getJobStatus(UUID jobId) {
return (QueueAndPublish) currentJob.get().stream()
.filter(j -> j.getJobId()==jobId)
.collect(Collectors.toList());
}
#Override
public List<QueueAndPublish> getAllJobStatus() {
return currentJob.get();
}
#Override
public QueueAndPublish getCategoryDataProcess() {
List<QueueAndPublish> processList=new ArrayList<QueueAndPublish>();
QueueAndPublish process=QueueAndPublish.builder()
.jobId(UUID.randomUUID())
.jobName("Name for Job")
.jobStatus("Not Yet Started")
.build();
Thread t1=new Thread(process.getJobId().toString()){
#Override
public void run(){
log.info("How are you doing");
process.setJobStatus("Completed");
}
};
t1.start();
processList.add(process);
currentJob.set(processList);
return process;
}
#Override
public QueueAndPublish getCatgeoryDataProcessStatus() {
return null;
}
}
package de.summer.sampleapplayerv1.domain;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.UUID;
#Getter
#Setter
#Builder
#Entity
public class QueueAndPublish implements Serializable {
#Id
private UUID jobId;
private String jobName;
private String jobStatus;
}
If I remove the constructor, spring boot application is starting up without any errors. If included , start up is failing with unsatisfied dependency errors.
Can someone please help on what is wrong with config?
You expect Spring to create an instance of class QueueAndPublishServiceImpl for the implementation of QueueAndPublishService. This instance needs a constructor parameter of type AtomicReference<List<QueueAndPublish>> injected.
But you obviously do not define any Spring bean (Bean, Component, Service, ...) of that type.
Edit:
public QueueAndPublishServiceImpl(
#Qualifier("currentJob") AtomicReference<List<QueueAndPublish>> currentJob
){
this.currentJob=currentJob;
}
Here you define a constructor parameter to have a AtomicReference<List<QueueAndPublish>>, and even specify it with a #Qualifier. So you need to provide a Spring bean of this class with this qualifier, otherwise Spring cannot inject it into the constructor call.
Consider defining a bean of type 'java.util.concurrent.atomic.AtomicReference' in your configuration.
Means "something like" adding this to your Sampleapplayerv1Application:
#Bean("currentJob") AtomicReference<List<QueueAndPublish>> currentJob() {
// or a list implementation of your choice.
return new AtomicReference<>(new java.util.ArrayList<>());
}

Failed to create query for method public abstract

Simple I want test my application to connect with database to insert
some record statically.
it properly work or not.but it throws this type of error that i
mentioned below;
I donot know where i make mistake,I define everything properly
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'turistRepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract com.main.ToursTravels.model.Turist com.main.ToursTravels.repo.TuristRepo.findByName(java.lang.String)! No property name found for type Turist!
turistrepo.java
package com.main.ToursTravels.repo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.main.ToursTravels.model.Turist;
#Repository
public interface TuristRepo extends CrudRepository<Turist, Long> {
Turist findByName(String turistname);
}
vechiletyperepo.java
package com.main.ToursTravels.repo;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.main.ToursTravels.model.Turist;
import com.main.ToursTravels.model.VechileType;
#Repository
public interface VechileTypeRepo extends CrudRepository<VechileType, Long> {
List<VechileType> findByTurist(Turist turist , Sort sort);
}
mainclasss.java
package com.main.ToursTravels;
import java.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.main.ToursTravels.model.Turist;
import com.main.ToursTravels.model.VechileKind;
import com.main.ToursTravels.model.VechileType;
import com.main.ToursTravels.repo.TuristRepo;
import com.main.ToursTravels.repo.VechileTypeRepo;
#SpringBootApplication
public class ToursTravelsApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(ToursTravelsApplication.class, args);
}
#Autowired
TuristRepo trp;
#Autowired
VechileTypeRepo vtrp;
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
Turist trs = new Turist();
trs.setTuristname("NewsWels");
trs.setTravelkm(100);
trs.setTraveldate(LocalDate.of(2020, 20, 11));
trs.setDrivername("prabhka5r");
VechileType vtp= new VechileType();
vtp.setVechilekind(VechileKind.SEDAN);
vtp.setRateperkm(6);
vtp.setMinprice(2530.00);
trs.setVechileno("GJ05K2619");
trs.setTotalamount(15186.00);
trs.setBookingstatus(true);
trs.setVechiletype(vtp);
vtp.setTurist(trs);
trp.save(trs);
}
}
turist.java
package com.main.ToursTravels.model;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.Data;
#Entity
#Table(name="turist")
#Data
public class Turist {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="truist_id")
private Long truistid;
#Column(name="turistname")
private String turistname;
#Column(name="travel_km")
private int travelkm;
#Column(name="travel_date")
private LocalDate traveldate;
#Column(name="drivername")
private String drivername;
#OneToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
#JoinColumn(name="booking_id")
private VechileType vechiletype;
#Column(name="vechileno")
private String vechileno;
#Column(name="total_amount")
private Double totalamount;
#Column(name="BOOKING_status")
private boolean bookingstatus;
public Turist(){}
public Turist(String turistname, int travelkm, LocalDate traveldate, String drivername, VechileType vechiletype,
String vechileno, Double totalamount, boolean bookingstatus) {
super();
this.turistname = turistname;
this.travelkm = travelkm;
this.traveldate = traveldate;
this.drivername = drivername;
this.vechiletype = vechiletype;
this.vechileno = vechileno;
this.totalamount = totalamount;
this.bookingstatus = bookingstatus;
}
}
VechileType.java
package com.main.ToursTravels.model;
import java.math.BigDecimal;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import lombok.Data;
#Entity
#Table(name="vechiletype")
#Data
public class VechileType {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="booking_id")
private Long bookingid;
#OneToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL,mappedBy="vechiletype")
private Turist turist;
#Enumerated(EnumType.STRING)
#Column(name="vechilekind")
private VechileKind vechilekind;
#Column(name="rate_per_km")
private int rateperkm;
#Column(name="miniprice")
private Double minprice;
public VechileType(){}
public VechileType(Turist turist, VechileKind vechilekind, int rateperkm, Double minprice) {
this.turist = turist;
this.vechilekind = vechilekind;
this.rateperkm = rateperkm;
this.minprice = minprice;
}
}
Your Repository method references a name field for your Turist class, but none exists. You have turistname available to query.
So your method name should be this:
Turist findByTuristname(String turistname);

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