Error creating bean By #Resource - java

I am tiring to to build a small application with spring+hibernate+maven+postgreSQL but when i am tiring to inject dependency in my controller and service class it creates problem for injecting the dependency here is the code and logs please give your suggestion to solve this wiring problem?
mvc-dispature-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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">
<context:component-scan base-package="com.bms" />
<context:annotation-config />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/bms" />
<property name="username" value="postgres" />
<property name="password" value="*******" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.bms.Domain.Book</value>
</list>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
Controller class BooksEntryController.java
#Controller
#RequestMapping(value = "/dashboard/*")
public class BooksEntryController {
#Resource
private BookFormService bookFormServiceImp;
#RequestMapping(value = "/booksentryform", method = RequestMethod.GET)
public ModelAndView viewBooksEntryForm(Model model) {
model.addAttribute("test", new Book());
return new ModelAndView("bookregistrationform");
}
#RequestMapping(value = "/addbookdetails", method = RequestMethod.POST)
public String addBook(#ModelAttribute("test") Book book, Model model) {
if (book != null) {
bookFormServiceImp.addBooks(book);
return "bookaddsuccessfully";
} else {
throw new NullPointerException();
}
}
}
Service interface BookFormService.java
public interface BookFormService {
void addBooks(Book book);
}
ServiceImp class BookFormServiceImp.java
#Service("bookFormServiceImp")
public class BookFormServiceImp implements BookFormService {
#Resource
private BookFormDao bookFormDaoImp ;
public void addBooks(Book book) {
bookFormDaoImp.addBook(book);
// TODO Auto-generated method stub
}
}
Dao interface BookFormDao .java
public interface BookFormDao {
public void addBook(Book book); }
DaoImp class BookFormDaoImp.java
#Repository("bookFormDaoImp")
public class BookFormDaoImp implements BookFormDao {
#Resource
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public void addBook(Book book) {
// TODO Auto-generated method stub
getCurrentSession().save(book);
}
}
Here is the log :
2013-06-20 00:35:51.528:INFO:/bms:Initializing Spring root WebApplicationContext
Jun 20, 2013 12:35:51 AM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Jun 20, 2013 12:35:51 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Thu Jun 20 00:35:51 IST 2013]; root of context hierarchy
Jun 20, 2013 12:35:51 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]
Jun 20, 2013 12:35:52 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2df8f8: defining beans [booksEntryController,bookFormDaoImp,bookFormServiceImp,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,dataSource,sessionFactory,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Jun 20, 2013 12:35:52 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2df8f8: defining beans [booksEntryController,bookFormDaoImp,bookFormServiceImp,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,dataSource,sessionFactory,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Jun 20, 2013 12:35:52 AM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'booksEntryController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookFormServiceImp': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookFormDaoImp': Injection of resource dependencies failed; nested exception is java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:306)
...................................
....................................

You are probably not using the right sessionFactory class. If you are using Hibernate 4, use LocalSessionFactoryBean instead of AnnotationSessionFactoryBean.
Replace
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
by
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

Related

Hibernate Product is not mapped FROM Product

i use hibernate 5 and spring 4 mapped my class and used entity name in creating queries but i get
> SEVERE: Servlet.service() for servlet [dispatcher] in context with
> path [/emusicstore] threw exception [Request processing failed; nested
> exception is java.lang.IllegalArgumentException:
> org.hibernate.hql.internal.ast.QuerySyntaxException: Product is not
> mapped [FROM Product]] with root cause
> org.hibernate.hql.internal.ast.QuerySyntaxException: Product is not
> mapped
part of my codes that is necessary is included!
my controller
#Controller
public class HomeController {
#Autowired
private ProductDaoImpl productDaoImpl;
#RequestMapping(value = "/productList")
public String getProduct(Model model) {
List<Product> products = productDaoImpl.getAllProducts();
model.addAttribute("products", products);
return "productList";
}
My Product getting Function
public List<Product> getAllProducts() {
Session session;
try {
session = sessionFactory.getCurrentSession();
System.out.println("SDSDSASDASDASD");
} catch (HibernateException e) {
session = sessionFactory.openSession();
System.out.println("Error in session get all");
}
Query query = session.createQuery("FROM Product");
List<Product> products = query.list();
session.flush();
return products;
}
My applicattion 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:orcl" />
<property name="username" value="c##alireza" />
<property name="password" value="myjava123" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</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.mywebsite.contorller</value>
<value>com.mywebsite.dao.impl</value>
<value>com.mywebsite.model</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
tnx For ur help!
In order for Hibernate to recognize your entity class, the class must be annotated with #Entity and located in one of the packages defined in the property packagesToScan of your sessionFactory.

The requested resource is not available - Spring MVC

I am developing small student app, based on Spring MVC which should implement simple CRUD students operations via rest web services onto mysql database.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
mvc-dispatcher-servlet.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: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/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-3.0.xsd">
<context:property-placeholder location="classpath:database.properties" />
<context:component-scan base-package="com.training.dao" />
<context:component-scan base-package="com.training.service" />
<context:component-scan base-package="com.training.controller" />
<context:component-scan base-package="com.training.bean" />
<context:component-scan base-package="com.training.dto" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<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/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.training.bean.StudentBean</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
StudentsController.java:
package com.training.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.training.bean.StudentBean;
import com.training.dto.ResponseDTO;
import com.training.service.StudentService;
#RestController
#RequestMapping(value = "/student")
#EnableWebMvc
public class StudentController {
#Autowired
StudentService studentService;
ResponseDTO responseDTO;
#RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public #ResponseBody ResponseDTO getStudent(#PathVariable("id") int studentId) {
try {
StudentBean student = studentService.getStudent(studentId);
responseDTO = studentService.converToDTO(true, "success", student, null);
} catch (Exception e) {
responseDTO = studentService.converToDTO(false, e.getMessage(), null, null);
}
return responseDTO;
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public #ResponseBody ResponseDTO createStudent(#RequestBody StudentBean student) {
try {
studentService.addStudent(student);
responseDTO = studentService.converToDTO(true, "success", null, null);
} catch (Exception e) {
responseDTO = studentService.converToDTO(false, e.getMessage(), null, null);
}
return responseDTO;
}
#RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public #ResponseBody ResponseDTO deleteStudent(#PathVariable("id") int studentId) {
try {
studentService.deleteStudent(studentId);
responseDTO = studentService.converToDTO(true, "success", null, null);
} catch (Exception e) {
responseDTO = studentService.converToDTO(false, e.getMessage(), null, null);
}
return responseDTO;
}
#RequestMapping(value = "/getAll", method = RequestMethod.GET)
public #ResponseBody ResponseDTO getAllStudents() {
try {
java.util.List<StudentBean> students = studentService.getAllStudents();
responseDTO = studentService.converToDTO(true,"success", null, students);
} catch (Exception e) {
responseDTO = studentService.converToDTO(false,e.getMessage(), null, null);
}
return responseDTO;
}
#RequestMapping(value = "/about")
public String aboutPage() {
return "about";
}
}
Now when I call for example
localhost:8080/student/getAll
or any of the mapped methods the reponse is
HTTP Status 404 - /student/getAll
The requested resource is not available.
Here is catalina.out, no errors there:
Oct 22, 2016 10:23:17 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]
INFO: Mapped "{[/about/app]}" onto public java.lang.String com.training.controller.AboutController.aboutPage()
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/delete/{id}],methods=[GET]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.deleteStudent(int)
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/get/{id}],methods=[GET]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.getStudent(int)
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/getAll],methods=[GET]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.getAllStudents()
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/about]}" onto public java.lang.String com.training.controller.StudentController.aboutPage()
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/add],methods=[POST]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.createStudent(com.training.bean.StudentBean)
Oct 22, 2016 10:23:21 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: WebApplicationContext for namespace 'dispatcher-servlet': startup date [Sat Oct 22 10:23:17 EEST 2016]; root of context hierarchy
Oct 22, 2016 10:23:21 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization completed in 3912 ms
Oct 22, 2016 10:23:21 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Oct 22, 2016 10:23:21 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Oct 22, 2016 10:23:21 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 7653 ms
#EnableWebMvc applies to Spring configuration classes (i.e. classes annotated with #Configuration). It's not having any effect on your controller. From the first line of the #EnableWebMvc Javadoc page (emphasis mine):
Adding this annotation to an #Configuration class imports the Spring MVC configuration from WebMvcConfigurationSupport...
Since you're using XML configuration instead of Java Annotation driven configuration, simply add this to your mvc-dispatcher-servlet.xml: file:
<mvc:annotation-driven/>
As is, without this configuration active, Spring is trying to route to a view with the same name as your request mapping. Since it doesn't exist, you're getting the 404 Not Found error.

org.springframework.beans.factory.UnsatisfiedDependencyException: Unsatisfied dependency expressed through method 'anyMethodName' parameter 0:

I don't know what's wrong with this setup...
AVERTISSEMENT:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDao': Unsatisfied dependency expressed through method 'anyMethodName' parameter 0: Error creating bean with name 'sessionFactory' defined in class path resource [hbn-config.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.jboss.logging.Logger.debugf(Ljava/lang/String;I)V; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [hbn-config.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.jboss.logging.Logger.debugf(Ljava/lang/String;I)V
juil. 03, 2016 6:56:50 PM org.springframework.cache.ehcache.EhCacheManagerFactoryBean destroy
INFOS: Shutting down EhCache CacheManager
juil. 03, 2016 6:56:50 PM org.springframework.web.context.ContextLoader initWebApplicationContext
GRAVE: Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDao': Unsatisfied dependency expressed through method 'anyMethodName' parameter 0: Error creating bean with name 'sessionFactory' defined in class path resource [hbn-config.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.jboss.logging.Logger.debugf(Ljava/lang/String;I)V; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [hbn-config.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.jboss.logging.Logger.debugf(Ljava/lang/String;I)V
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:651)
UserDao :
#Repository
public class UserDao extends AbstractDao<User> {
private static Logger LOG = LoggerFactory.getLogger(UserDao.class);
public UserDao() {
}
public List<User> findAllUsers() {
Query q = getHibernateTemplate()
.getSessionFactory()
.openSession()
.createQuery("from " + entityClass.getSimpleName());
List<User> list = q.list();
return list;
}
AbstractDao :
public abstract class AbstractDao<E> extends CustomHibernateDaoSupport {
protected final Class<E> entityClass;
#SuppressWarnings("unchecked")
public AbstractDao() {
entityClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
protected HibernateTemplate getOneResultTemplate() {
HibernateTemplate oneResultTemplate = createHibernateTemplate(getSessionFactory());
oneResultTemplate.setMaxResults(1);
return oneResultTemplate;
}
protected Query createQuery(String queryString) {
return getSessionFactory().getCurrentSession().createQuery(queryString);
}
#Transactional(readOnly = false)
public void save(E entity) {
getHibernateTemplate().save(entity);
}
#Transactional(readOnly = false)
public void saveOrUpdate(E entity) {
getHibernateTemplate().saveOrUpdate(entity);
}
#Transactional(readOnly = false)
public void update(E entity) {
getHibernateTemplate().update(entity);
}
#Transactional(readOnly = false)
public void delete(E entity) {
getHibernateTemplate().delete(entity);
}
#SuppressWarnings("unchecked")
public List<E> list() {
Query q = getHibernateTemplate().getSessionFactory().openSession()
.createQuery("from " + entityClass.getSimpleName());
return q.list();
}
CustomHibernateDaoSupport :
public abstract class CustomHibernateDaoSupport extends HibernateDaoSupport {
#Autowired
public void anyMethodName(SessionFactory sessionFactory) {
setSessionFactory(sessionFactory);
}
}
webappContext :
<?xml version="1.0" encoding="UTF-8"?>...
<cache:annotation-driven />
<context:property-placeholder location="classpath:app.properties" />
<!-- Auto scan the components -->
<context:annotation-config />
<context:component-scan base-package="com.example" />
<bean id="applicationContextHolder"
class="com.example.myproject.core.util.ApplicationContextHolder" />
<import resource="classpath:hbn-config.xml" />
<import resource="classpath:cache-config.xml" />
hbn-config :
<?xml version="1.0" encoding="UTF-8"?>...
<!-- Hibernate session factory -->
<tx:annotation-driven />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- Hibernate session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop>
<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">${hibernate.temp.use_jdbc_metadata_defaults}</prop>
<prop key="hibernate.order_inserts">${hibernate.order_inserts}</prop>
<prop key="hibernate.order_updates">${hibernate.order_updates}</prop>
</props>
</property>
<property name="packagesToScan" value="com.example.myproject.core.model" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<aop:config>
<aop:pointcut id="serviceMethods"
expression="execution(*com.example.myproject.core.dao.*Dao.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false" />
<!-- <tx:method name="save*" propagation="REQUIRED" read-only="false"
/> -->
<!-- <tx:method name="add*" propagation="REQUIRED" read-only="false" /> -->
<!-- <tx:method name="update*" propagation="REQUIRED" read-only="false"
/> -->
<!-- <tx:method name="delete*" propagation="REQUIRED" read-only="false"
/> -->
<!-- <tx:method name="export*" propagation="REQUIRED" read-only="false"
/> -->
<!-- <tx:method name="import*" propagation="REQUIRED" read-only="false"
/> -->
</tx:attributes>
</tx:advice>
</beans>
The version of jboss-logging in the classpath is different than that expected by Hibernate.

Spring won't instantiate and I keep getting this infinite loop

I'm trying to find out what have I done wrong. It would be great if anyone could help me. I keep getting this in an infinite loop:
May 02, 2015 9:41:57 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#799f7e29: startup date [Sat May 02 21:41:57 EEST 2015]; root of context hierarchy
May 02, 2015 9:41:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
May 02, 2015 9:41:57 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#548a9f61: startup date [Sat May 02 21:41:57 EEST 2015]; root of context hierarchy
May 02, 2015 9:41:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
UsersDAOImp :
public class UsersDAOImp extends GenericEntityDAO implements UsersDAO {
private SessionFactory sessionFactory = (SessionFactory) BeanManager.getBean("sessionFactory");
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<Users> selectAll() {
Session session = getSessionFactory().getCurrentSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(Users.class);
List<Users> users = (List<Users>) criteria.list();
session.getTransaction().commit();
return users;
}
}
UsersService
public class UsersService {
UsersDAOImp usersDAO = new UsersDAOImp();
public void setUsersDAO(UsersDAOImp usersDAO) {
this.usersDAO = usersDAO;
}
public UsersDAOImp getUsersDAO() {
return usersDAO;
}
public List<Users> getAllUsers() {
return getUsersDAO().selectAll();
}
}
Bean manager used to get context
public class BeanManager {
/* BeanManager is used to parse Beans.xml file */
private static ApplicationContext context;
private BeanManager() {
}
public static ApplicationContext getContext() {
return context;
}
public static void setContext(ApplicationContext context) {
BeanManager.context = context;
}
public static Object getBean(String beanId) {
if (context == null) {
context = new ClassPathXmlApplicationContext("Beans.xml");
}
Object result = context.getBean(beanId);
return result;
}
}
This is my Beans.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:tx="http://www.springframework.org/schema/tx"
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-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="usersDAO" class="com.survey.persistance.DAO.UsersDAOImp" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<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/app" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
</beans>

Hibernate 4 + Spring + getHibernateTemplate().getSessionFactory().getCurrentSession()

Want to use Spring to automatically work with Hibernate 4 sessions
Also I like to extends DAO, for not create many DAO for many entities
But there is problem:
SessionDAO.java
public abstract class SessionDAO extends HibernateDaoSupport{
public void startSession() {
getSession().beginTransaction();
}
public void closeSession() {
getSession().getTransaction().commit();
}
public void addObject() {
startSession();
getSession().save(this);
closeSession();
}
public Session getSession()
{
return getHibernateTemplate().getSessionFactory().getCurrentSession();
}
}
Values.java
#Entity
#Table
public class Values extends SessionDAO {
private int valuesId;
private double amount;
private Date date;
//...getters, setters, etc
}
dispatcher-servlet.xml
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>entity.Crypto</value>
<value>entity.Values</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#my.****.us-east-1.rds.amazonaws.com:1521:ORCL" />
<property name="username" value="****" />
<property name="password" value="****" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
When start server, receive:
INFO: HHH000206: hibernate.properties not found
When try to load page receive:
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
on line
return getHibernateTemplate().getSessionFactory().getCurrentSession();
What's wrong?
Don't get the session by extend HibernateDaoSupport, just inject SessionFactory in DAO.
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}

Categories

Resources