Results 1 to 6 of 6

Thread: ClassCastException ParameterizedType

  1. #1

    Default ClassCastException ParameterizedType

    I am getting a strange exception when trying to configure annotated JPA transactions. Running in Tomcat, Spring 2.5.4, Hibernate 3.2.5, cglib 2.2

    My context:
    Code:
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    	<property name="entityManagerFactory" ref="entityManagerFactory"/>
    	<property name="dataSource" ref="dataSource"/>
    </bean>	
    
    <bean id="entityManagerFactory"
    	class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    	<property name="persistenceUnitName" value="p1" />
    	<property name="dataSource" ref="dataSource" />
    	<property name="persistenceXmlLocation" value="classpath:persistence.xml" />
    	<property name="jpaVendorAdapter">
    		<bean
    			class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    			<property name="showSql" value="true" />
    			<property name="generateDdl" value="true" />
    			<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
    		</bean>
    	</property>
    </bean>
    class that's blowing up on startup:
    Code:
    Transactional
    @Repository
    public abstract class BaseDao<T extends Serializable, K extends Serializable> {
    	@PersistenceContext
    	protected EntityManager entityMgr;
    	private  Class<T> tClass;
    
    	@SuppressWarnings("unchecked")
    	protected BaseDao(){
    		this.entityMgr = null;
    
    		log.debug("*** genericSuperclass(): " + getClass().getGenericSuperclass());	
    		this.tClass = (Class<T>) ((ParameterizedType) getClass()
                    .getGenericSuperclass()).getActualTypeArguments()[0];
    	}
    }

    And the exception:
    Code:
    2008-06-19 23:31:52,484 DEBUG [net.mycompany.dao.BaseDao] - <*** genericSuperclass(): net.mycompany.dao.BaseDao<net.mycompany.pm.Address, java.lang.Long>>
    2008-06-19 23:31:52,796 DEBUG [net.mycompany.dao.BaseDao] - <*** genericSuperclass(): class net.mycompany.dao.AddressDAO>
    2008-06-19 23:31:52,937 INFO [org.hibernate.impl.SessionFactoryImpl] - <closing>
    2008-06-19 23:31:52,953 ERROR [org.springframework.web.context.ContextLoader] - <Context initialization failed>
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'addressDAO' defined in ServletContext resource [/WEB-INF/classes/hibernateSpringContext.xml]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class net.mycompany.dao.AddressDAO]: Common causes of this problem include using a final class or a non-visible class; nested exception is net.sf.cglib.core.CodeGenerationException: java.lang.ClassCastException-->java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:478)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:220)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
    	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:729)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:381)
    	at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
    	at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
    	at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
    	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3764)
    No idea why the constructor is called twice. If I remove the <tx:annotation-driven/>, spring has no problem loading... but i get no transaction mangement with out it. You can see the debug being called twice, and only when <tx:annotation-driven> is present in config.
    I have not found anyone else experiencing the same problem. Any clue as to what it means?

    Help, please.

  2. #2
    Join Date
    Aug 2005
    Posts
    9

    Default Same Error

    ysbelman,

    I am having the exact same problem. Applying the @Transactional annotation causes the problem. I am using a GenericDAO, same as your BaseDAO. Have you found a solution to this? I can use everything fine, but when I want to apply the transaction annotation it bombs out.


    Caused by: org.springframework.aop.framework.AopConfigExcepti on: Could not generate CGLIB subclass of class [class com.retailstore.dao.StoreIPDAO]: Common causes of this problem include using a final class or a non-visible class; nested exception is net.sf.cglib.core.CodeGenerationException: java.lang.ClassCastException-->java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
    at org.springframework.aop.framework.Cglib2AopProxy.g etProxy(Cglib2AopProxy.java:207)
    at org.springframework.aop.framework.ProxyFactory.get Proxy(ProxyFactory.java:110)
    at org.springframework.aop.framework.autoproxy.Abstra ctAutoProxyCreator.createProxy(AbstractAutoProxyCr eator.java:490)
    at org.springframework.aop.framework.autoproxy.Abstra ctAutoProxyCreator.wrapIfNecessary(AbstractAutoPro xyCreator.java:365)
    at org.springframework.aop.framework.autoproxy.Abstra ctAutoProxyCreator.postProcessAfterInitialization( AbstractAutoProxyCreator.java:325)
    at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.applyBeanPostProcessors AfterInitialization(AbstractAutowireCapableBeanFac tory.java:361)
    at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.initializeBean(Abstract AutowireCapableBeanFactory.java:1344)
    at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:473)
    ... 29 more
    Caused by: net.sf.cglib.core.CodeGenerationException: java.lang.ClassCastException-->java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
    at net.sf.cglib.core.ReflectUtils.newInstance(Reflect Utils.java:235)
    at net.sf.cglib.core.ReflectUtils.newInstance(Reflect Utils.java:220)
    at net.sf.cglib.core.ReflectUtils.newInstance(Reflect Utils.java:216)
    at net.sf.cglib.proxy.Enhancer.createUsingReflection( Enhancer.java:640)
    at net.sf.cglib.proxy.Enhancer.firstInstance(Enhancer .java:538)
    at net.sf.cglib.core.AbstractClassGenerator.create(Ab stractClassGenerator.java:225)
    at net.sf.cglib.proxy.Enhancer.createHelper(Enhancer. java:377)
    at net.sf.cglib.proxy.Enhancer.create(Enhancer.java:2 85)
    at org.springframework.aop.framework.Cglib2AopProxy.g etProxy(Cglib2AopProxy.java:201)
    ... 36 more

    Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
    at com.retailstore.dao.GenericDAO.<init>(GenericDAO.j ava:21)
    at com.retailstore.dao.StoreIPDAO.<init>(StoreIPDAO.j ava:15)
    at com.retailstore.dao.StoreIPDAO$$EnhancerByCGLIB$$4 d474fc9.<init>(<generated>)
    at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Construc tor.java:513)
    at net.sf.cglib.core.ReflectUtils.newInstance(Reflect Utils.java:228)


    Please let me know what you did... I'm lost here. I guess I will have to keep digging.

  3. #3
    Join Date
    Aug 2005
    Posts
    9

    Default

    Ok, after doing some research, I have determined that typically, the Transactional annotations belong in the service layer. They should be removed from the DAO layer. Make sure that the service layer implements and interface. I believe that you will need to annotate the method with 'Transactional' and have that method implement the interface in order for it to work.

    Thanks,
    David

  4. #4

    Default

    exactly. The lack of interfaces affected the proxying. I fixed it this way:

    Code:
    @Transactional
    @Repository
    public abstract class BaseDao<T extends Serializable, K extends Serializable> implements IBaseDAO<T, K> {
    	
    	@PersistenceContext
    	protected EntityManager entityMgr;
        private  Class<T> tClass;
    Code:
    @Transactional
    @Repository
    public class AddressDAO  extends BaseDao<Address, Long> implements IAddressDAO {
    	protected final static Log log = LogFactory.getLog(AddressDAO.class);
    
    }
    Code:
    public interface IAddressDAO extends IBaseDAO<Address, Long>{
    }
    Code:
    public interface IBaseDAO<T extends Serializable, K extends Serializable> {
    	
    	void create(T entity);
    	T retrieve(K key);
    	T update(T entity);
    	void delete(K key);
    
    }
    Spring config
    Code:
    <bean id="addressDao" class="net.company.dao.AddressDAO" />
    accessing:
    Code:
    @Autowired
    private IAddressDAO addressDAO;
    or access yourself via context:
    Code:
    IAddressDAO addressDAO =  (IAddressDAO)ctx.getBean("addressDAO");
    This should help.

  5. #5

    Default Code not working

    Hi YSbelman, im trying to work this example but im getting an exception:

    Exception in thread "main" java.lang.NullPointerException
    at data.test.EventDAO.getAll(EventDAO.java:43)
    at data.test.EventDAO.getAll(EventDAO.java:1)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknow n Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Un known Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.aop.support.AopUtils.invokeJoi npointUsingReflection(AopUtils.java:309)
    at org.springframework.aop.framework.ReflectiveMethod Invocation.invokeJoinpoint(ReflectiveMethodInvocat ion.java:183)
    at org.springframework.aop.framework.ReflectiveMethod Invocation.proceed(ReflectiveMethodInvocation.java :150)
    at org.springframework.transaction.interceptor.Transa ctionInterceptor.invoke(TransactionInterceptor.jav a:110)
    at org.springframework.aop.framework.ReflectiveMethod Invocation.proceed(ReflectiveMethodInvocation.java :172)
    at org.springframework.aop.framework.JdkDynamicAopPro xy.invoke(JdkDynamicAopProxy.java:202)
    at $Proxy15.getAll(Unknown Source)
    at data.test.Main.main(Main.java:20)

    ______________________________________________

    Here is my Event DAO

    public class EventDAO extends BaseDao<Event, Long> implements IEventsDAO{

    @Override
    public void create(Event entity) {
    // TODO Auto-generated method stub

    }


    @Override
    public Event retrieve(Long key) {
    // TODO Auto-generated method stub
    Query query = entityMgr.createQuery("SELECT * FROM Event WHERE id = 1");
    return (Event) query.getResultList();

    }


    @Override
    public Event update(Event entity) {
    // TODO Auto-generated method stub
    return null;
    }

    @Override
    public void delete(Long key) {
    // TODO Auto-generated method stub

    }


    @Override
    public List<Event> getAll(Long key) {
    // TODO Auto-generated method stub
    Query query = entityMgr.createQuery("SELECT * FROM Events");
    return (List<Event>) query.getResultList();
    }

    }

    ______________________________________________
    I added an additional method getAll().
    Im trying to run it through a main method:


    public static void main(String[] args) {
    // TODO Auto-generated method stub

    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext .xml");
    IEventsDAO eventsDAO = (IEventsDAO)ctx.getBean("eventDao");
    List<Event> events = (List<Event>) eventsDAO.getAll(new Long(1));
    for(Event e: events)
    System.out.println(e.getName());
    }

  6. #6
    Join Date
    Sep 2005
    Location
    Webster Groves, MO
    Posts
    95

    Default

    Another thing to try is to modify the setting of the proxy-target-class attribute to the <tx:annotation-driven> element. I got this error after setting it to false:

    HTML Code:
    <tx:annotation-driven proxy-target-class="true" />
    I removed that (I was trying to solve another problem by adding it) so that it was:

    HTML Code:
    <tx:annotation-driven />
    Note that the default is false for that attribute.

    Once I had done that, this error went away (my other error was still there, but as it happens the cause was non-Spring-related, but the problem was just manifesting in the Spring code).
    HTH.
    Rick Herrick

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •