I am trying to create e-commerce in spring. After including "Hibernate" and "H2" database in my project, I get the error. The error is given below. I am trying very much but not found any solution.
Error:
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.home.dao.ProductDao
com.home.controller.homeController.productDao; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'productDaoImpl': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private org.hibernate.SessionFactory
com.home.dao.impl.ProductDaoImpl.sessionFactory; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'sessionFactory' defined in ServletContext
resource [/WEB-INF/applicationContext.xml]: Invocation of init method
failed; nested exception is
org.hibernate.exception.GenericJDBCException: Unable to open JDBC
Connection for DDL execution
applicationContext.xml
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:~/test" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.home</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
home-servlet.xml
<context:component-scan base-package="com.home">
<context:include-filter type="aspectj" expression="com.home.*" />
</context:component-scan>
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:resources mapping="/resources/**"
location="/WEB-INF/resources/" cache-period="31556926" />
<tx:annotation-driven />
web.xml
<display-name>Archetype Created Web Application</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/home-servlet.xml,
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<servlet>
<servlet-name>home</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
homeController.java
#Controller
#Configuration
public class homeController {
#Autowired
private ProductDao productDao;
#RequestMapping("/")
public String home() {
return "views/home";
}
#RequestMapping("/productList")
public String getProducts(Model model) {
List<Product> products = productDao.getAllProducts();
model.addAttribute("products", products);
return "views/productList";
}
#RequestMapping("/productList/viewProduct/{productId}")
public String viewProduct(#PathVariable String productId, Model model) throws IOException{
Product product = productDao.getProductById(productId);
model.addAttribute(product);
return "views/viewProduct";
}
}
ProductDaoImpl.java
#Repository
#Transactional
public class ProductDaoImpl implements ProductDao {
#Autowired
private SessionFactory sessionFactory;
public void addProduct(Product product) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(product);
session.flush();
}
public Product getProductById(String id) {
Session session = sessionFactory.getCurrentSession();
Product product = (Product) session.get(Product.class, id);
session.flush();
return product;
}
public List<Product> getAllProducts() {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Product");
List<Product> products = query.list();
session.flush();
return products;
}
public void deleteProduct (String id) {
Session session = sessionFactory.getCurrentSession();
session.delete(getProductById(id));
session.flush();
}
}
Product.java Code:
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String productId;
private String productName;
private String productCategory;
private String productDescription;
private double productPrice;
private String productCondition;
private String productStatus;
private int unitInStock;
private String productManufacturer;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCategory() {
return productCategory;
}
public void setProductCategory(String productCategory) {
this.productCategory = productCategory;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public double getProductPrice() {
return productPrice;
}
public void setProductPrice(double productPrice) {
this.productPrice = productPrice;
}
public String getProductCondition() {
return productCondition;
}
public void setProductCondition(String productCondition) {
this.productCondition = productCondition;
}
public String getProductStatus() {
return productStatus;
}
public void setProductStatus(String productStatus) {
this.productStatus = productStatus;
}
public int getUnitInStock() {
return unitInStock;
}
public void setUnitInStock(int unitInStock) {
this.unitInStock = unitInStock;
}
public String getProductManufacturer() {
return productManufacturer;
}
public void setProductManufacturer(String productManufacturer) {
this.productManufacturer = productManufacturer;
}
}
ProductDao.java Code:
public interface ProductDao {
void addProduct(Product product);
Product getProductById(String id);
List<Product> getAllProducts();
void deleteProduct(String id);
}
Project Structure or Directory Image:
Project Structure or Directory at my Eclipse Oxygen IDE
Finally, I have found my own problems when I use IntelliJ IDEA IDE. Problems are given bellow:
My problem have occurred at pom.xml file. Here, I have used hibernate-core latest version (5.4.0.Final) dependency which is not support import org.hibernate.Query; package and also not support Query query = session.createQuery("from Product"); and Product product = (Product) session.get(Product.class, id); codes at ProductDaoImpl.java class.
I have also used latest version of spring-webmvc, spring-core and spring-orm dependency at pom.xml file. For that it occurs version conflict.
Solution:
Forget Eclipse and avoid it. Please use IntelliJ IDEA. This is very user friendly IDE for Java Spring MVC framework and also show what wrong you do.
Create new project and used hibernate-core 4.0.1.Final version dependency at pom.xml file and also used 4.2.8.RELEASE version of own, spring-core and spring-orm dependencies.
Remove import org.hibernate.Query.query; package from ProductDaoImpl.java class and put import org.hibernate.Query package.
Thank you :)
ProductDao is not a bean..That's why. Repository, controller, service are all of type of bean. Make sure this is which type of bean.....Thank you.
Related
So i'm building a spring 3.2.3.RELEASE / hibernate 4.0.1.FINAL application and i got the following exception
[2017-03-22 09:29:47,860] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory [localhost-startStop-1] Ignoring bean creation exception on FactoryBean type check: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginService' defined in URL [jar:file:/D:/Programmes/apache-tomcat-7.0.33/webapps/perWeb/WEB-INF/lib/perService-2.0.jar!/applicationContext-transactional-service.xml]: Cannot resolve reference to bean 'loginServiceImpl' while setting bean property 'target'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginServiceImpl' defined in URL [jar:file:/D:/Programmes/apache-tomcat-7.0.33/webapps/perWeb/WEB-INF/lib/perService-2.0.jar!/applicationContext-simple-service.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'ma.dao.impl.GenericDAO' to required type 'ma.dao.IGenericDAO' for property 'dao'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [ma.dao.impl.GenericDAO] to required type [ma.dao.IGenericDAO] for property 'dao': no matching editors or conversion strategy found
Here is my beans: loginservice
<bean id="loginService"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManagerPER" />
</property>
<property name="target">
<ref bean="loginServiceImpl" />
</property>
<property name="transactionAttributes">
<props>
<prop key="loadUserByUsername">
PROPAGATION_REQUIRED,-Exception
</prop>
</props>
</property>
</bean>
loginServiceImpl
<bean id="loginServiceImpl"
class="ma.service.login.LoginService">
<property name="dao">
<ref bean="userDAO" />
</property>
</bean>
UserDAO
<bean id="userDAO"
class="ma.dao.impl.GenericDAO">
<constructor-arg>
<value>
ma.dao.mappings.Utilisateur
</value>
</constructor-arg>
<property name="sessionFactory">
<ref bean="sessionFactoryPER" />
</property>
</bean>
Utilisateur.Java
#Entity
#NamedQueries(
{
#NamedQuery(name="findUtilisateurByName",
query = "select user from Utilisateur user where user.login=:userName"
)
}
)
public class Utilisateur implements java.io.Serializable {
private static final long serialVersionUID = 7214071893495381842L;
private Integer id;
private Profil profil;
private String nom;
private String prenom;
private String login;
private String passwd;
public Utilisateur() {
}
public Utilisateur(Integer id) {
this.id = id;
}
#Id #GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne
public Profil getProfil() {
return profil;
}
public void setProfil(Profil profil) {
this.profil = profil;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
Am i missing somthing ?
If you need more informations please let me know
It seems like your GenericDao not able to convert to IGenericDao and for that, there might be several reasons like is your GenericDao implements the IGenericDao, etc.
Also the following link might be useful if you are implementing GenericDao pattern:
https://www.codeproject.com/Articles/251166/The-Generic-DAO-pattern-in-Java-with-Spring-and
I am a newbie in spring and hibernate and have been studying and exploring the power these technologies bring to enterprise development. However I am stuck with a program im trying to run which keeps throwing the following errors. I found similar issue on here and have done everything suggested but still get same error.
**WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productController': Unsatisfied dependency expressed through field 'itemMasterDao': Cannot find class [org.apache.commons.dbcp2.BasicDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/inventory-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp2.BasicDataSource; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.apache.commons.dbcp2.BasicDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/inventory-servlet.xml]; nested exception is java.lang.ClassNotFoundException:** org.apache.commons.dbcp2.BasicDataSource
Aug 30, 2016 12:14:29 AM org.springframework.web.servlet.DispatcherServlet initServletBean
SEVERE: Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productController': Unsatisfied dependency expressed through field 'itemMasterDao': Cannot find class [org.apache.commons.dbcp2.BasicDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/inventory-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp2.BasicDataSource; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.apache.commons.dbcp2.BasicDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/inventory-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp2.BasicDataSource
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:350)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1238)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1151)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1038)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5337)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.apache.commons.dbcp2.BasicDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/inventory-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp2.BasicDataSource
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1357)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:628)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:597)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1450)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:446)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:424)
at org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:220)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1048)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1018)
inventory-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.chills.hspring.product.controller, com.chills.hspring.product.dao" />
<bean id="itemMasterDao" class="com.chills.hspring.product.dao.ItemMasterDAOImpl">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="j123456" />
</bean>
<bean id="sessionFactory" Class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/Pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
<servlet>
<servlet-name>inventory</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>inventory</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/test
</property>
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<!-- Display all generated SQL to stdout -->
<property name="show_sql">true</property>
<mapping class="com.chills.hspring.dto.ItemMaster" />
</session-factory>
</hibernate-configuration>
ItemMasterDAOImpl.java
package com.chills.hspring.product.dao;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
import com.chills.hspring.dto.ItemMaster;
#Transactional
public class ItemMasterDAOImpl implements ItemMasterDAO {
private SessionFactory sessionFactory;
public ItemMasterDAOImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void add(ItemMaster item) {
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
session.save(item);
}catch(HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
}
#Override
public void update(ItemMaster item) {
Session session = sessionFactory.getCurrentSession();
try {
System.out.println("IN UPDATE");
session.beginTransaction();
session.saveOrUpdate(item);
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
}
#Override
public ItemMaster getItem(Long id) {
Session session = sessionFactory.getCurrentSession();
ItemMaster item = null;
try {
System.out.println("IN GETITEM");
session.beginTransaction();
item = (ItemMaster) session.get(ItemMaster.class, id);
}catch(HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return item;
}
#Override
public void delete(Long id) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
ItemMaster item = (ItemMaster)session.get(ItemMaster.class, id);
if(null != item) {
session.delete(item);
}
session.getTransaction().commit();
}
#SuppressWarnings({ "deprecation", "unchecked" })
#Override
public List<ItemMaster> list() {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
List<ItemMaster> items = null;
try {
System.out.println("IN LIST");
items = (List<ItemMaster>)session.createQuery("from ItemMaster").list();
}catch(HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return items;
}
}
ItemMasterDAO.java
package com.chills.hspring.product.dao;
import java.util.List;
import com.chills.hspring.dto.*;
public interface ItemMasterDAO {
public List<ItemMaster> list();
public void add(ItemMaster item);
public void update(ItemMaster item);
public ItemMaster getItem(Long id);
public void delete(Long id);
}
ItemMaster.java
package com.chills.hspring.dto;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="ItemMaster")
public class ItemMaster implements Serializable {
private static final long serialVersionUID = 45369355259515150L;
private Long item_code;
private String item_name;
private double price;
private int qty;
#Temporal(TemporalType.DATE)
#Column (name="createdOn")
private Date createdOn;
public Date getCreatedOn()
{
return createdOn;
}
public void setCreatedOn(Date createdOn)
{
this.createdOn = createdOn;
}
#Id
#GeneratedValue
#Column(name="item_code")
public Long getItem_code()
{
return item_code;
}
public void setItem_code(Long item_code)
{
this.item_code = item_code;
}
#Column(name="item_name")
public String getItem_name()
{
return item_name;
}
public void setItem_name(String item_name)
{
this.item_name = item_name;
}
#Column(name="price")
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}
#Column (name="qty")
public int getQty()
{
return qty;
}
public void setQty(int qty)
{
this.qty = qty;
}
}
ProductController.java
package com.chills.hspring.product.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.portlet.ModelAndView;
import com.chills.hspring.product.dao.*;
import com.chills.hspring.dto.ItemMaster;
#Controller
public class ProductController {
#Autowired
private ItemMasterDAO itemMasterDao;
#RequestMapping(value="/list")
public ModelAndView list() {
List<ItemMaster> itemList = itemMasterDao.list();
ModelAndView model = new ModelAndView("itemMasterList");
model.addObject("itemList",itemList);
return model;
}
#RequestMapping(value="/loadAddForm")
public ModelAndView add() {
ModelAndView model = new ModelAndView("ItemMasterAdd");
ItemMaster item = new ItemMaster();
model.addObject("item", item);
List<ItemMaster> itemList = itemMasterDao.list();
model.addObject("itemList",itemList);
return model;
}
#RequestMapping(value="/edit")
public ModelAndView edit(#RequestParam(value="id", required = true)Long id) {
System.out.println("Id = "+ id);
ModelAndView model = new ModelAndView("ItemMasterAdd");
ItemMaster item = itemMasterDao.getItem(id);
model.addObject("item", item);
List<ItemMaster>itemList = itemMasterDao.list();
model.addObject("itemList",itemList);
return model;
}
#RequestMapping(name="/delete")
public ModelAndView delete(#RequestParam(value="id", required = true)Long id) {
ModelAndView model = new ModelAndView("ItemMasterAdd");
itemMasterDao.delete(id);
List<ItemMaster> itemList = itemMasterDao.list();
model.addObject("itemList", itemList);
return model;
}
#RequestMapping(name="/save", method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("item")ItemMaster item) {
System.out.println(item.getItem_name());
if(null != item)
itemMasterDao.add(item);
ModelAndView model = new ModelAndView("ItemMasterAdd");
item = new ItemMaster();
model.addObject("item",item);
List<ItemMaster> itemList = itemMasterDao.list();
model.addObject("itemList", itemList);
return model;
}
#RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView update(#ModelAttribute("item")ItemMaster item) {
System.out.println(item.getItem_name());
if(null != item)
itemMasterDao.update(item);
ModelAndView model = new ModelAndView("ItemMasterAdd");
item = new ItemMaster();
model.addObject("item",item);
List<ItemMaster> itemList = itemMasterDao.list();
model.addObject("itemList", itemList);
return model;
}
}
Missing JAR for org.apache.commons.dbcp2.BasicDataSource
Add this to pom.xml dependencies or download the jar and place it in the classpath
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
I was trying to get data from a MySQL database using the Spring utility ResultSetExtractor, but I got the following exception:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'edao' defined in class path resource [applicationContext2.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'jdbcTemplate' of bean class [org.resultset.EmployeeDao]: Bean property 'jdbcTemplate' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1067)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:562)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at org.resultset.Test.main(Test.java:11)
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'jdbcTemplate' of bean class [org.resultset.EmployeeDao]: Bean property 'jdbcTemplate' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1012)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:857)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1341)
... 13 more
Employee.java
public class Employee {
private int id;
private String name;
private float salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public Employee(int id, String name, float salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
public Employee()
{
}
}
EmployeeDao.java
public class EmployeeDao {
private JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Employee> getAllEmployees(){
return template.query("select * from employee",new ResultSetExtractor<List<Employee>>(){
#Override
public List<Employee> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Employee> list=new ArrayList<Employee>();
while(rs.next()){
Employee e=new Employee();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getInt(3));
list.add(e);
}
return list;
}
});
}
}
Test.java
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext2.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
List<Employee> list=dao.getAllEmployees();
for(Employee e:list)
System.out.println(e);
}
}
and applicationContext2.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://loclahost:3306/test1" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="org.resultset.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
These all are java files I am using. It says the setter's return type doesn't match with the getter's, but I checked it, and it is correct there.
The problem is in
<bean id="edao" class="org.resultset.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
Try changing the name="jdbcTemplate" to name="template". Since you have given name as jdbcTemplate spring will search for a setter method with name setJdbcTemplate() in EmployeeDao class, but the acutal method you have is setTemplate()
Controller extends MethodNameResolver
public final void setMethodNameResolver(
MethodNameResolver methodNameResolver) {
this.methodNameResolver = methodNameResolver;
}
public final MethodNameResolver getMethodNameResolver() {
return this.methodNameResolver;
}
remove spring Annotation like #controller #AutoWired
i use Hibernate 4 and Spring 3.
i have two entity.
Book entity
#Entity
#Table(name = "book")
public class Book implements Serializable {
public Book() {
}
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue( strategy = GenerationType.IDENTITY)
private int id;
#ManyToOne()
#JoinColumn( name = "author_id" )
private Author author;
private String name;
private int pages;
#Version
#Column( name = "VERSION")
private int version;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
}
and Author entity
#Entity
#Table(name = "author")
public class Author implements Serializable {
public Author() {
}
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue( strategy = GenerationType.IDENTITY)
private int id;
private String name;
#OneToMany( mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Book> books = new HashSet<Book>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
public void addBook(Book book) {
book.setAuthor(this);
getBooks().add(book);
}
public void removeBook(Book book) {
getBooks().remove(book);
}
}
and JSON depend in pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate4</artifactId>
<version>2.1.2</version>
</dependency>
My Root-context is here -
<!-- Root Context: defines shared resources visible to all other web components -->
<context:annotation-config/>
<context:component-scan base-package="org.jar.libs.dao" />
<context:component-scan base-package="org.jar.libs.service" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/hibernate"
p:username="root" p:password="root" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>org.jar.libs.domain.Book</value>
<value>org.jar.libs.domain.Author</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
...servlet-context.xml
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="org.jar.libs.controller" />
Controller.
#Controller
#RequestMapping (value = "books/rest")
public class BookController {
#Autowired
private BookService bookService;
// logger
private static final Logger logger = LoggerFactory.getLogger(BookController.class);
#SuppressWarnings("unchecked")
#RequestMapping( method = RequestMethod.GET )
public #ResponseBody List<Book> getBook() {
List<Book> res = bookService.findAll();
return res;
}
}
findAll in my DAO :
public List<Book> findAll() {
Session session = sessionFactory.getCurrentSession();
List<Book> result = (List<Book>) session.createQuery("select c from Book c").list();
return result;
}
in debug i see that method return 2 records, but Spring can not convert result to JSON and return 406 HTTP error. What's wrong?
I attach image what i see in debug. - http://tinypic.com/view.php?pic=35kvi9i&s=6
Generally, when you call getter methods of entity classes(which returns relation object) out of transaction, then you get LazyInitializationExceptions.
That's what might be happening in your case if you are converting entity class objects(retrieved from query) to json out of transaction.
I had same issue, I converted my entity object retrieved by hibernate to json in controller. As controller was out of transaction(Transaction at service layer), while converting to json, getter methods of entity class objects are called and I got LazyInitializationException. Which obstructed object conversion to json, and response was not returned.
My solution, Try this :
#SuppressWarnings("unchecked")
#RequestMapping( method = RequestMethod.GET )
public #ResponseBody List<Book> getBook() {
List<Book> res = bookService.findAll();
for(Book book : res) {
book.getAuthor().setBooks(null);
}
return res;
}
As others have suggested,
I would really not advise you to try to JSON serialize (or actually perform any serialization) of hibernate entities.
You must remember that the fetched entities are actually "proxified" objects (Hibernate uses ASM, CGLIB and other "dynamic proxiy" frameworks).
As a result for example, collections get replaced with [PersistenceBags] which may be initialized "lazily" , and cause you hibernate exceptions 1.
But the problems do not stop there, you may see issues when trying to serialize an Hibernate custom type
I know this might sound you like writing "boillerplate" code but you might end up coding DTOs - data transfer objects which will take the entity returned from your DAL, and transform them to an object that can be serialized.
You can use a framework like dozer in order to ease development of serialization between an entity to a DTO.
Try using these two Jackson artifacts instead
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.9</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.9</version>
</dependency>
Also on your controller try by changing it to -
#SuppressWarnings("unchecked")
#RequestMapping( method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE )
public #ResponseBody List<Book> getBook() {
Lastly, make sure your view is making a json request.
I really want to understand what is going on with my code.
I have a standalone application which uses spring and Hibernate as JPA and I am trying to run the test using a single main Class
My main class
package edu.acct.tsegay.common;
import edu.acct.tsegay.model.User;
import edu.acct.tsegay.business.IUserBusinessObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
try {
ApplicationContext context = new ClassPathXmlApplicationContext(
"Spring3AndHibernate-servlet.xml");
IUserBusinessObject userBusinessObject = (IUserBusinessObject) context
.getBean("userBusiness");
User user = (User) context.getBean("user1");
user.setPassword("pass");
user.setUsername("tsegay");
System.out.println(user.getPassword());
userBusinessObject.delete(user);
User user2 = new User();
user2.setUsername("habest");
user2.setPassword("pass1");
System.out.println(user2.getPassword());
/*
* userBusinessObject.save(user2);
*
* User user3 = userBusinessObject.searchUserbyId("tsegay");
* System.out.println("Search Result: " + user3.getUsername());
*/
System.out.println("Success");
} catch (Exception e) {
e.printStackTrace();
}
}
}
my application context is:
<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-2.5.xsd">
<!-- data source -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="test" />
<property name="password" value="password" />
</bean>
<!-- session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- exposed person business object -->
<bean id="userBusiness" class="edu.acct.tsegay.business.UserBusinessObject">
<property name="userDao" ref="userDao" />
</bean>
<bean id="user1" class="edu.acct.tsegay.model.User">
<property name="username" value="tse" />
<property name="password" value="pass" />
</bean>
<!-- Data Access Object -->
<bean id="userDao" class="edu.acct.tsegay.dao.UserDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
My User Model is:
package edu.acct.tsegay.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Version;
import org.hibernate.annotations.NaturalId;
#Entity
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;
private Integer VERSION;
#Version
public Integer getVERSION() {
return VERSION;
}
public void setVERSION(Integer vERSION) {
VERSION = vERSION;
}
#NaturalId
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
My DAO is:
package edu.acct.tsegay.dao;
import edu.acct.tsegay.model.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
#Repository
public class UserDao implements IUserDao {
private SessionFactory sessionFactory;
private HibernateTemplate hibernateTemplate;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
public void save(User user) {
// TODO Auto-generated method stub
// getHibernateTemplate().save(user);
this.hibernateTemplate.save(user);
}
public void delete(User user) {
// TODO Auto-generated method stub
this.hibernateTemplate.delete(user);
}
public User searchUserbyId(String username) {
// TODO Auto-generated method stub
return this.hibernateTemplate.get(User.class, username);
}
}
And this my stacktrace error when i run the program:
pass
org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: edu.acct.tsegay.model.User; nested exception is org.hibernate.MappingException: Unknown entity: edu.acct.tsegay.model.User
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:679)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:837)
at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:833)
at edu.acct.tsegay.dao.UserDao.delete(UserDao.java:34)
at edu.acct.tsegay.business.UserBusinessObject.delete(UserBusinessObject.java:30)
at edu.acct.tsegay.common.App.main(App.java:23)
Caused by: org.hibernate.MappingException: Unknown entity: edu.acct.tsegay.model.User
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:580)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1365)
at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:100)
at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:74)
at org.hibernate.impl.SessionImpl.fireDelete(SessionImpl.java:793)
at org.hibernate.impl.SessionImpl.delete(SessionImpl.java:771)
at org.springframework.orm.hibernate3.HibernateTemplate$25.doInHibernate(HibernateTemplate.java:843)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
... 6 more
You have to list your classes in your session factory configuration. You can have your entities auto-discovered if you are using EntityManager.
In order to use annotations with hibernate and spring, you have to use AnnotationSessionFactoryBean:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="annotatedClasses">
<list>
<value>edu.acct.tsegay.model.User</value>
</list>
</property>
....
</bean>
Also, it is rather strange that your User entity is a spring bean. You don't need that. Hibernate entities are supposed to be created with the new operator.
I've encountered the same problem and didn't find any good answer for this
What worked for me was to declare my entity class in the persistence.xml file:
<persistence ...>
<persistence-unit ...>
<class>com.company.maenad.core.model.News</class>
<class>com.company.maenad.core.model.AdExtraInfo</class>
</persistence-unit>
</persistence>
In addition to Bozho answer, if you are using spring + hibernate with annotation then in your session factory bean you can register your bean like below:
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(appContext.getBean(HikariDataSource.class));
localSessionFactoryBean.setAnnotatedClasses(
AppUser.class, Assignment.class
);