Tuesday, 8 April 2014

Spring 4 + Hibernate 4: ClassCastException with LocalSessionFactoryBean and SessionFactory

By meant of Spring libraries we have to develope a DAL (Data Access Layer)
in a form of a jar library that will be alien into a sure application.I
wish to use Hibernate to opening a MySQL DB and DBCP for a supervision of
a connectors pool.I have combined a config record DALConfig.java that
contains a settlement of a DAL beans:package my.dal.config;import
java.util.Properties;import javax.annotation.Resource;import
org.apache.commons.dbcp2.BasicDataSource;import
org.apache.commons.dbcp2.BasicDataSourceFactory;import
org.springframework.context.annotation.Bean;import
org.springframework.context.annotation.ComponentScan;import
org.springframework.context.annotation.Configuration;import
org.springframework.context.annotation.PropertySource;import
org.springframework.core.env.Environment;import
org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;import
org.springframework.orm.hibernate4.HibernateTransactionManager;// Needed
by Spring to supplement this category to a ApplicationContext's
configuration@Configuration@ComponentScan(basePackages = { "my.dal.config"
})// Property record in that are combined a MySQL tie
properties@PropertySource("classpath:dbconnection.properties")public
category DALConfig { private stationary final String
PROPERTY_NAME_DATABASE_DRIVER = "db.driver"; private stationary final
String PROPERTY_NAME_DATABASE_PASSWORD = "db.password"; private
stationary final String PROPERTY_NAME_DATABASE_URL = "db.url";
private stationary final String PROPERTY_NAME_DATABASE_USERNAME =
"db.username"; private stationary final String
PROPERTY_NAME_POOL_INITIAL_SIZE = "pool.initialsize"; private
stationary final String PROPERTY_NAME_POOL_MAX_IDLE = "pool.maxidle";
// Needed to opening ability record @Resource private Environment
environment; // The bean that defines a BasicDataSource (DBCP) @Bean
open BasicDataSource dataSource() throws Exception {
Properties props = new Properties(); props.put("driverClassName",
environment.getProperty(PROPERTY_NAME_DATABASE_DRIVER));
props.put("url", environment.getProperty(PROPERTY_NAME_DATABASE_URL));
props.put("username",
environment.getProperty(PROPERTY_NAME_DATABASE_USERNAME));
props.put("password",
environment.getProperty(PROPERTY_NAME_DATABASE_PASSWORD));
props.put("initialSize",
environment.getProperty(PROPERTY_NAME_POOL_INITIAL_SIZE));
props.put("maxIdle",
environment.getProperty(PROPERTY_NAME_POOL_MAX_IDLE));
BasicDataSource bds = BasicDataSourceFactory.createDataSource(props);
relapse bds; } // Bean used to interpret Hibernate's exceptions
into Spring's ones @Bean open
PersistenceExceptionTranslationPostProcessor
persistenceExceptionTranslationPostProcessor() {
PersistenceExceptionTranslationPostProcessor b = new
PersistenceExceptionTranslationPostProcessor(); relapse b;
}}Then we wrote a HibernateConfig.java config record that contains a
Hibernate settlement stuffpackage my.dal.hibernateconfig;import
java.util.Properties;import javax.annotation.Resource;import
javax.sql.DataSource;import org.hibernate.SessionFactory;import
org.springframework.beans.factory.annotation.Autowired;import
org.springframework.context.annotation.Bean;import
org.springframework.context.annotation.ComponentScan;import
org.springframework.context.annotation.Configuration;import
org.springframework.context.annotation.PropertySource;import
org.springframework.core.env.Environment;import
org.springframework.orm.hibernate4.HibernateTransactionManager;import
org.springframework.orm.hibernate4.LocalSessionFactoryBean;@Configuration@ComponentScan(basePackages
= { "my.dal.hibernatesessionfactory"
})@PropertySource("classpath:dbconnection.properties")public category
HibernateConfig { private stationary final String
PROPERTY_NAME_DAL_CLASSES_PACKAGE = "hibernate.dal.package"; private
stationary final String PROPERTY_NAME_HIBERNATE_DIALECT =
"hibernate.dialect"; @Resource private Environment environment;
@Autowired DataSource dataSource; // Bean that defines a
FactoryBean for a SessionBean @Bean open LocalSessionFactoryBean
sessionFactory() { LocalSessionFactoryBean lsfb = new
LocalSessionFactoryBean();
lsfb.setPackagesToScan(PROPERTY_NAME_DAL_CLASSES_PACKAGE);
Properties hibernateProperties = new Properties();
hibernateProperties.put("dialect", PROPERTY_NAME_HIBERNATE_DIALECT);
lsfb.setHibernateProperties(hibernateProperties);
lsfb.setDataSource(dataSource); relapse lsfb; } @Bean open
HibernateTransactionManager transactionManager() { // THE
EXCEPTION IS THROWN AT THIS LINE HibernateTransactionManager htm =
new HibernateTransactionManager((SessionFactory) sessionFactory());
relapse htm; }}Next we wrote a UserDAO.java category that is a DAO for
a User category that models a DB's User table.package my.dal.dao;import
my.models.User;import org.hibernate.SessionFactory;import
org.springframework.beans.factory.annotation.Autowired;import
org.springframework.stereotype.Component;import
org.springframework.stereotype.Repository;import
org.springframework.transaction.annotation.Transactional;@Component@Repository@Transactionalpublic
category UserDAO{ private SessionFactory sessionFactory; @Autowired
open UserDAO(SessionFactory sessionFactory) {
this.sessionFactory=sessionFactory; } open int insert(User user) {
relapse (Integer) sessionFactory.getCurrentSession().save(user); }
open User getByUsername(String username) { relapse (User)
sessionFactory.getCurrentSession().get(User.class, username); } open
vacant update(User user) {
sessionFactory.getCurrentSession().merge(user); // .update(user); }
open vacant delete(String username) { User u =
getByUsername(username);
sessionFactory.getCurrentSession().delete(u); }}The mapping category
User.java (generated controlling a Eclipse's Hibernate tools) ispackage
my.models;public category User implements java.io.Serializable {
private String username; private String idUserKeystone; private
String firstName; private String lastName; private String password;
private String email; private String emailRef; private String
employer; private boolean confirmed; // Getters, setters and full
constructor}Now we wish to exam a DAL. The contrast category is
DALTest.javapackage my.dal.tests;import stationary
org.junit.Assert.assertTrue;import my.dal.config.DALConfig;import
my.dal.dao.UserDAO;import my.dal.hibernateconfig.HibernateConfig;import
my.models.User;import org.hibernate.SessionFactory;import
org.junit.Test;import org.junit.runner.RunWith;import
org.springframework.beans.factory.annotation.Autowired;import
org.springframework.test.context.ContextConfiguration;import
org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@ContextConfiguration(classes
= { DALConfig.class,
HibernateConfig.class})@RunWith(SpringJUnit4ClassRunner.class)public
category DALTest { @Autowired UserDAO userDAO; @Test open
vacant testGetUser() { User user = null; // Let's see if a
user "myuser" is into a database user =
userDAO.getByUsername("myuser"); assertTrue(null != user);
}}When we run a exam it throws a following
exceptionsjava.lang.IllegalStateException: Failed to bucket
ApplicationContext ... Caused by:
org.springframework.beans.factory.BeanCreationException: Error formulating
bean with name 'transactionManager' tangible in category
my.dal.hibernateconfig.HibernateConfig: Instantiation of bean failed;
nested difference is
org.springframework.beans.factory.BeanDefinitionStoreException: Factory
slight [public
org.springframework.orm.hibernate4.HibernateTransactionManager
my.dal.hibernateconfig.HibernateConfig.transactionManager()] threw
exception; nested difference is java.lang.ClassCastException:
org.springframework.orm.hibernate4.LocalSessionFactoryBean$$EnhancerBySpringCGLIB$$d866ed45
can't be ban to org.hibernate.SessionFactory ... Caused by:
java.lang.ClassCastException:
org.springframework.orm.hibernate4.LocalSessionFactoryBean$$EnhancerBySpringCGLIB$$d866ed45
can't be ban to org.hibernate.SessionFactory during
my.dal.hibernateconfig.HibernateConfig.transactionManager(HibernateConfig.java:55)
during
my.dal.hibernateconfig.HibernateConfig$$EnhancerBySpringCGLIB$$bd53a036.CGLIB$transactionManager$1()
during
my.dal.hibernateconfig.HibernateConfig$$EnhancerBySpringCGLIB$$bd53a036$$FastClassBySpringCGLIB$$119f2c5b.invoke()
...It seems like a problem is a ban during a
lineHibernateTransactionManager htm = new
HibernateTransactionManager((SessionFactory) sessionFactory())On a
contrary, a Internet is full of instance minute that line that way. What
could be a problem?Thank we in advance

No comments:

Post a Comment