UnsatisfiedDependencyException: Spring MVC project fails to start because of Unsatisfied Dependency - spring

I am trying to start a spring mvc application,
and keep receiving the following error which I cannot solve
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerController': Unsatisfied dependency expressed through field 'customerDAO'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerDAOImpl': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-mvc-crud-demo-servlet.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
And this is only the first error shown in the console.
Well, I am trying to understand the first part of the whole line, which is
Unsatisfied dependency expressed through field customerDAO Unsatisfied dependency expressed through field customerDAO. It is giving a 500 server error. I cannot find any similar solution, neither see where the error is. Here are my source code files so far:
the entity class
package com.wcorp.springdemo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="customer")
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
public Customer() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
the dao Interface and its implementation
import com.wcorp.springdemo.entity.Customer;
public interface CustomerDAO {
public List<Customer> getCustomers();
}
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.wcorp.springdemo.entity.Customer;
#Repository
public class CustomerDAOImpl implements CustomerDAO {
// need to inject the session factory
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<Customer> getCustomers() {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create a query
Query<Customer> theQuery =
currentSession.createQuery("from Customer", Customer.class);
// execute query and get result list
List<Customer> customers = theQuery.getResultList();
// return the results
return customers;
}
}
The controller
package com.wcorp.springdemo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.wcorp.springdemo.dao.CustomerDAO;
import com.wcorp.springdemo.entity.Customer;
#Controller
#RequestMapping("/customer")
public class CustomerController {
// need to inject the customer dao
#Autowired
private CustomerDAO customerDAO;
#RequestMapping("/list")
public String listCustomers(Model theModel) {
// get customers from the dao
List<Customer> theCustomers = customerDAO.getCustomers();
// add the customers to the model
theModel.addAttribute("customers", theCustomers);
return "list-customers";
}
}
Here is the spring config file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.wcorp.springdemo" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC" />
<property name="user" value="springstudent2" />
<property name="password" value="springstudent2" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.wcorp.springdemo.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
the project build path, jars and tomcat server is fine eclipse is not complaining, spring version is 5.0.2, hibernate version 5.2.17

I found a similar problem described here
Please try to run under Java 8. The problem comes that you use Java 11.
Most of the frameworks are not compatible and are not fully tested on Java 11.

Related

How to fix the Autowired dependencies failing in spring-mvc Hibernate

Hello (i am a new Spring MVC Hibernate developper) and i am working on a user regestration application in Spring MVC and Hibernate using Netbeans. I have a problem and i can not resolve it; it's #Autowired and beans problem.
This my Entity, User:
#Entity
#Table(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
/* attributes */
#Column(name = "Username")
private String userName;
#Column(name = "Email")
private String email;
#Column(name = "Firstname")
private String firstName;
#Column(name = "LastName")
private String lastName;
#Column(name = "BirthDate")
private String birthDate;
#Column(name = "PhoneNumber")
private String phoneNumber;
#Column(name = "PWHash")
private String pwHash;
}
The DAO interface
package com.Etravals.DAO;
import com.Etravels.Model.User;
public interface UserDAO {
public void addUser(User user);
}
DAO Impl:
import com.Etravels.Model.User;
import javax.transaction.Transactional;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
#Transactional
public class UserDAOImpl implements UserDAO{
#Autowired
private SessionFactory sessionFactory;
private Session getSession(){
return sessionFactory.getCurrentSession();
}
#Override
public void addUser(User user) {
Session session = getSession();
session.save(user);
}
}
and service inteface :
package com.Etravels.Service;
import com.Etravels.Model.User;
public interface UserService {
public void addUser(User user);
}
Service Impl :
package com.Etravels.Service;
import com.Etravals.DAO.UserDAO;
import com.Etravels.Model.User;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
#Transactional
public class UserServiceImpl implements UserService{
#Autowired
private UserDAO userdao;
#Override
public void addUser(User user) {
userdao.addUser(user);
}
}
My HomeController :
#Controller
public class HomeController {
#Autowired
private UserService userService;
#RequestMapping(value="/")
public String showIndex(){
return "acceuil";
}
#RequestMapping(value="/addUser", method = RequestMethod.POST)
public ModelAndView addUser(#ModelAttribute("userFormSignUp") User user){
userService.addUser(user);
return new ModelAndView("redirect:/");
}
}
and this is my dispatcher-servlet.xml file :
<context:component-scan base-package="com.Etravels" />
<!-- Getting Database properties -->
<context:property-placeholder location="classpath:application.properties" />
<mvc:resources mapping="/resources/**" location="/resources/"/>
<mvc:resources mapping="/img/**" location="/resources/img/" />
<mvc:resources mapping="/styles/**" location="/resources/styles/"/>
<mvc:resources mapping="/javascript/**" location="/resources/javascript/"/>
<mvc:annotation-driven />
<!-- View Resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- DataSource -->
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
id="dataSource">
<property name="driverClassName" value="${database.driver}"></property>
<property name="url" value="${database.url}"></property>
<property name="username" value="${database.user}"></property>
<property name="password" value="${database.password}"></property>
</bean>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
<property name="packagesToScan" value="com.Etravels.Model"></property>
</bean>
<!-- Transaction -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
This is what I have as an error from Apache Tomcat server log :
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'homeController':
Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException:
Could not autowire field:
private com.Etravels.Service.UserService com.Etravels.Controller.HomeController.userService; nested exception is
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'userServiceImpl':
Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException:
Could not autowire field:
private com.Etravals.DAO.UserDAO com.Etravels.Service.UserServiceImpl.userdao; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.Etravals.DAO.UserDAO] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProc ....
Try
#Autowired(required=true)
private SessionFactory sessionFactory;
In UserDAOImpl class.

How to catch Spring bean creation error - Injection of autowired dependency?

AdminService.java
package service;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import dao.IAdminDAO;
import dao.IMemberDAO;
public interface AdminService
{
public HashMap<String, Object> adminLogin(String id,String pw);
}
AdminServiceImple.java
package service;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import dao.IAdminDAO;
#Service
public class AdminServiceImple implements AdminService
{
#Autowired
private IAdminDAO adminDao;
#Override
public HashMap<String, Object> adminLogin(String id, String pw)
{
HashMap<String, Object> adminResult = adminDao.selectOne(id);
if(adminResult != null)
{
String opwd = (String) adminResult.get("pw");
if(opwd.equals(pw))
{
if(adminResult.get("authority").equals(true))
{
return adminResult;
}
else
{
return null;
}
}
else
{
return null;
}
}
else
{
return null;
}
}
}
AdminController.java
package controller;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import service.AdminService;
import service.AdminServiceImple;
import service.MemberService;
#Controller
public class AdminController
{
#Autowired
public AdminServiceImple adminService;
// 관리자 로그인 폼 페이지
#RequestMapping("admin.do")
public String adminLoginPage()
{
return "adminLoginPage";
}
// 관리자 로그인했을 시 요청
#RequestMapping("adminLoginOK.do")
#ResponseBody
public String adminMainPage(#RequestParam(required=false) String id, #RequestParam(required=false)String pw,HttpSession session,HttpServletRequest req,HttpServletResponse resp)
{
HashMap<String, Object> adminLoginIdentify = adminService.adminLogin(id, pw);
if(adminLoginIdentify != null)
{
return "1";
}
else
{
return "0";
}
}
#RequestMapping("adminPage.do")
public String adminPage(HttpSession session,HttpServletRequest resquest,HttpServletResponse response) throws IOException
{
return "adminMainPage";
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:component-scan base-package="dao, service" />
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property value="com.mysql.jdbc.Driver" name="driverClassName"></property>
<property value="jdbc:mysql://localhost/rachelvf" name="url"></property>
<property value="root" name="username"/>
<property value="mysql" name="password"/>
</bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath:dao/mapper/*.xml"></property>
<property name="typeAliasesPackage" value="model"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperFactoryBean" id="memberDao">
<property name="mapperInterface" value="dao.IMemberDAO"></property>
<property name="sqlSessionFactory" ref="SqlSessionFactory"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperFactoryBean" id="adminDao">
<property name="mapperInterface" value="dao.IAdminDAO"></property>
<property name="sqlSessionFactory" ref="SqlSessionFactory"></property>
</bean>
</beans>
that is error code.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adminServiceImple': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dao.IAdminDAO service.AdminServiceImple.adminDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.IAdminDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
I thought about the cause of the error, but I think it is because I did not insert the service annotation.
However, there is no typos in any way, and everything is written correctly and errors occur. Is there something I don't know?
Can you tell me what caused this error?
And what about the solution?
make sure that AdminDao bean is creating and injecting correctly into
AdminServiceImple
use this tag in your spring-cfg.xml file
<context:component-scan base-package="dao" />
and also scan the controller class using --
<context:component-scan base-package="controller" />
you have to give information of class which are going to use annotation to IOC container to create bean...
A mapper is registered to Spring by including a MapperFactoryBean in your XML config file like follows:
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
try this to scan your Service Package and Dao Package.
<context:component-scan base-package="dao, service" />
above code will scan the dao and service package respectively.

Spring Hibernate JPA HSQL Table not found in statement

I'm training Spring persistence with LocalContainerEntityManagerFactoryBean and getting error:
Caused by: java.sql.SQLException: Table not found in statement [insert into PERSON (ID, email, name) values (null, ?, ?)]
Don't really know what I did wrong
My Main class (for test only)
package com.me.test;
import com.me.model.Person;
import com.me.service.PersonService;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
/**
*
*/
public static final Logger log = Logger.getLogger(Main.class.getName());
public static void main(String[] args) {
log.info("************** BEGINNING PROGRAM **************");
ApplicationContext context = new ClassPathXmlApplicationContext("WEB-INF/spring-config.xml");
PersonService personService = (PersonService) context.getBean("personService");
Person person = new Person();
person.setName("name");
person.setEmail("name#name.com");
personService.addPerson(person);
log.info("Person : " + person + " added successfully");
List<Person> persons = personService.fetchAllPersons();
log.info("The list of all persons = " + persons);
log.info("************** ENDING PROGRAM *****************");
}
}
My application context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.me" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="persistenceUnitName" value="personPersistenceUnit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="HSQL" />
<property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:file:/home/me/Pulpit/hsql1/db3; shutdown=true" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<bean id="dbUtil" class="com.me.service.DbUtil">
<!-- init-method="initialize">-->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="1.0">
<persistence-unit name="personPersistenceUnit" transaction-type="RESOURCE_LOCAL" >
<class>com.me.model.Person</class>
</persistence-unit>
</persistence>
PersonService class
package com.me.service;
import com.me.dao.PersonDao;
import com.me.model.Person;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class PersonService {
private PersonDao personDao;
public PersonDao getPersonDao() {
return personDao;
}
#Autowired
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public void addPerson(Person person) {
getPersonDao().insert(person);
}
public List<Person> fetchAllPersons() {
return getPersonDao().selectAll();
}
}
personDAO class
package com.me.dao;
import com.me.model.Person;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
#Repository("personDao")
#Transactional(propagation = Propagation.REQUIRED)
public class PersonDao {
private static final String SELECT_QUERY = "select p from Person p";
#PersistenceContext
private EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void insert(Person person) {
entityManager.persist(person);
}
public List<Person> selectAll() {
Query query = entityManager.createQuery(SELECT_QUERY);
List<Person> persons = (List<Person>) query.getResultList();
return persons;
}
}
What's wrong here guys?
edit:
adding person class:
package com.me.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "PERSON")
public class Person implements Serializable{
private Integer id;
private String name;
private String email;
#Id
#GeneratedValue
#Column(name = "ID")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", email=" + email + "]";
}
}
and persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="1.0">
<persistence-unit name="personPersistenceUnit" transaction-type="RESOURCE_LOCAL" >
<class>com.me.model.Person</class>
</persistence-unit>
</persistence>
The problem is that you have not told Hibernate anywhere that it needs to create the tables when it loads.
An easy way to do that would be to add
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
inside persistence.xml after <class>

Autowiring Controller doesn't work after adding entityManagerFactory bean

I've wrote a spring mvc webserver which uses NEO4j as data backend. Now i want to expand this with cassandra, so the server should be able to use both databases.
I have followed these 2 tutorials on how to combine Kundera (A JPA based Cassandra API):
https://github.com/impetus-opensource/Kundera/wiki/Using-Kundera-with-Spring
https://code.google.com/p/kundera/wiki/HowToUseKunderaWithSpring
But i'm not able to add the entitymanagerfactory bean to my applicationcontext.xml file.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="cassandra_pu"/>
</bean>
When i do this, spring gives an error that it can not create any of the already existing controllers that my webserver uses.
Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'indexController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private bmsapp.service.DataBasePopulator bmsapp.controller.IndexController.dbPopulator; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] for bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private bmsapp.service.DataBasePopulator bmsapp.controller.IndexController.dbPopulator; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] for bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 22 more
Those controllers are created by using the #Controller annotation in their class files and by autowiring them in the files where they are used. This works fine normally but when i add the entityManagerFactory bean it suddenly stops working. How is this possible?
My applicationContext file currently looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
">
<!-- Scans the classpath for annotated components that will be auto-registered
as Spring beans. For example #Controller and #Service. -->
<context:component-scan base-package="bmsapp" />
<!-- Activate Spring Data Neo4j repository support -->
<neo4j:config storeDirectory="data/graph.db" base-package="bmsapp.domain" />
<neo4j:repositories base-package="bmsapp.repository" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="cassandra_pu"/>
</bean>
<tx:annotation-driven mode="proxy" />
<!-- context:annotation-config / -->
<!-- use this for Spring Jackson JSON support -->
<mvc:annotation-driven />
And my persistence.xml file:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="cassandra_pu">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<properties>
<property name="kundera.nodes" value="localhost"/>
<property name="kundera.port" value="9160"/>
<property name="kundera.keyspace" value="KunderaExamples"/>
<property name="kundera.dialect" value="cassandra"/>
<property name="kundera.client.lookup.class" value="com.impetus.client.cassandra.pelops.PelopsClientFactory" />
<property name="kundera.cache.provider.class" value="com.impetus.kundera.cache.ehcache.EhCacheProvider"/>
<property name="kundera.cache.config.resource" value="/ehcache-test.xml"/>
</properties>
</persistence-unit>
SimpleComment domain class:
package bmsapp.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "SIMPLE_COMMENT", schema = "KunderaExamples#cassandra_pu")
#XmlRootElement(name = "SimpleComment")
public class SimpleComment {
#Id
#Column(name = "COMMENT_ID")
private int id;
#Column(name = "USER_NAME")
private String userName;
#Column(name = "COMMENT_TEXT")
private String commentText;
public SimpleComment() {
}
public SimpleComment(int commentId, String userName, String commentText) {
this.id = commentId;
this.userName = userName;
this.commentText = commentText;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCommentText() {
return commentText;
}
public void setCommentText(String commentText) {
this.commentText = commentText;
}
}
SpringExampleDao:
package bmsapp.repository;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import bmsapp.domain.SimpleComment;
#Service
public class SpringExampleDao
{
#PersistenceContext(type=PersistenceContextType.EXTENDED)
private EntityManager entityManager;
public SimpleComment addComment(int id, String userName, String commentText)
{
SimpleComment simpleComment = new SimpleComment(id, userName, commentText);
entityManager.persist(simpleComment);
return simpleComment;
}
public SimpleComment getCommentById(String Id)
{
SimpleComment simpleComment = entityManager.find(SimpleComment.class, Id);
return simpleComment;
}
public List<SimpleComment> getAllComments()
{
Query query = entityManager.createQuery("SELECT c from SimpleComment c");
List<SimpleComment> list = query.getResultList();
return list;
}
}
The relevant part of the stacktrace is:
nested exception is java.lang.ClassNotFoundException: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
So you need to add a dependency to spring-orm, see http://mvnrepository.com/artifact/org.springframework/spring-orm.
However, I'm not sure that really solves your problem. In the description you're mentioning Neo4j and I cannot see what part of your description relates to that.

#Autowired annotation

I have written a small code to check #Autowired annotation in Spring, here is my piece of code
public class Address
{
private String street;
private String City;
private String State;
private String Country;
/* getter setter here */
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Customer
{
private String name;
private Address address;
// other getter setter here
#Autowired
public void setAddress(Address address)
{
this.address = address;
}
}
and springexample.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="address1" class="org.springexamples.Address">
<property name="street" value="vihar" />
<property name="city" value="dehradun" />
<property name="state" value="Uttarakhand" />
<property name="country" value="India" />
</bean>
<bean id="addres2" class="org.springexamples.Address">
<property name="street" value="triveni vihar" />
<property name="city" value="dehradun" />
<property name="state" value="Uttarakhand" />
<property name="country" value="India" />
</bean>
<bean id="customer" class="org.springexamples.Customer">
<property name="name" value="deepak" />
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
</beans>
and main class
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AutowiredQualifierTest
{
public static void main(String[] args)
{
ApplicationContext context= new ClassPathXmlApplicationContext("springexample.xml");
Customer cust = (Customer)context.getBean("customer");
System.out.println(cust.getName() + " " + cust.getAddress().getStreet());
}
}
Ideally it should show an exception as two beans of the same type exist however its picking up bean with id="address1" so i am getting this bean behaviour.
No unique bean of type [org.springexamples.Address] is defined: expected single matching bean but found 2: [address1, addres2]..exception is coming..and it is clearly saying right..so you have to use #Qualifier(your_required_beanid)
for example:
#Qualifier("Address1")
then it will consider id with address1 bean
The exception is thrown. I bet you are doing something wrong. I have tested you code, just to be hundred percent sure and it throws the exception.
Let's take a look to the documentation:
3.4.5.1 Limitations and disadvantages of autowiring
Multiple bean definitions within the container may match the type specified by the setter method or constructor argument to be autowired. For arrays, collections, or Maps, this is not necessarily a problem. However for dependencies that expect a single value, this ambiguity is not arbitrarily resolved. If no unique bean definition is available, an exception is thrown
Also, take a look to this post.
This will give you exception, when spring tries to autoware the address field, it will not find any bean with id address ...rather user Qualifer with proper id so that while autowaring it will pinck the porper object of address from 2 id [address1, address2].

Resources