0

I tried different configurations but to no effect. The error remained the same. Here the desired config taken from BoneCPs web site:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.2.RELEASE.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.2.RELEASE.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
">    

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" autowire-candidate="" autowire="autodetect">
        <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>
                <prop key="hibernate.connection.provider_class">com.jolbox.bonecp.provider.BoneCPConnectionProvider</prop>
                <prop key="hibernate.connection.driver_class">org.postgresql.Driver</prop>
                <prop key="hibernate.connection.url">jdbc:postgresql:MyDB</prop>
                <prop key="hibernate.connection.username">postgres</prop>
                <prop key="hibernate.connection.password">123456</prop>
                <prop key="bonecp.idleMaxAge">240</prop>
                <prop key="bonecp.idleConnectionTestPeriod">60</prop>
                <prop key="bonecp.partitionCount">1</prop>
                <prop key="bonecp.acquireIncrement">5</prop>
                <prop key="bonecp.maxConnectionsPerPartition">60</prop>
                <prop key="bonecp.minConnectionsPerPartition">5</prop>
                <prop key="bonecp.statementsCacheSize">50</prop>
                <prop key="bonecp.releaseHelperThreads">2</prop>
            </props>
        </property>
    </bean>
    <!--<bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:annotation-driven transaction-manager="txManager" /> -->

    <bean id="AbstractHibernateDAO" abstract="true"
          class="org.bitbucket.myName.moleculedatabaseframework.dao.AbstractHibernateDAO"/>

    <bean id="ChemicalStructureDAO" extends="AbstractHibernateDAO"
          class="org.bitbucket.myName.moleculedatabaseframework.dao.ChemicalStructureDAO"/>
    <bean id="ChemicalCompoundDAO" extends="AbstractHibernateDAO"
          class="org.bitbucket.myName.moleculedatabaseframework.dao.ChemicalCompoundDAO"/>
</beans>

And code containing autowired session factory:

@Repository
public abstract class AbstractHibernateDAO< T extends Serializable> {

    private final Class< T> clazz;
    @Autowired
    SessionFactory sessionFactory;

    public AbstractHibernateDAO(final Class< T> clazzToSet){
        this.clazz = clazzToSet;
    }

    public T getById(final Long id) {
        Preconditions.checkArgument(id != null);
        return (T) this.getCurrentSession().get(this.clazz, id);
    }

    public List< T> getAll() {
        return this.getCurrentSession()
                .createQuery("from " + this.clazz.getName()).list();
    }

    public void create(final T entity) {
        Preconditions.checkNotNull(entity);
        this.getCurrentSession().persist(entity);
    }

    public void update(final T entity) {
        Preconditions.checkNotNull(entity);
        this.getCurrentSession().merge(entity);
    }

    public void delete(final T entity) {
        Preconditions.checkNotNull(entity);
        this.getCurrentSession().delete(entity);
    }

    public void deleteById(final Long entityId) {
        final T entity = this.getById(entityId);
        Preconditions.checkState(entity != null);
        this.delete(entity);
    }

    protected final Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }
}

When trying to create a new entity (last line of snippet) I get an error:

ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); 

ChemicalStructureDAO structureDAO = (ChemicalStructureDAO) context.getBean("ChemicalStructureDAO");

ChemicalStructure structure1 = new ChemicalStructure();
structure1.setStructureKey("c1ccccc1");
structure1.setStructureData("c1ccccc1");

structureDAO.create(structure1);

I'm getting a NullPointerException:

java.lang.NullPointerException
    at org.bitbucket.myName.moleculedatabaseframework.dao.AbstractHibernateDAO.getCurrentSession(AbstractHibernateDAO.java:78)
    at org.bitbucket.myName.moleculedatabaseframework.dao.AbstractHibernateDAO.create(AbstractHibernateDAO.java:54)
    at org.bitbucket.myName.moleculedatabaseframework.App.main(App.java:32)
------------------------------------------------------------------------

Maybe I missunderstood what autowired means? I thought that that property will be set automatically. So I tried following:

ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); 
SessionFactory sessionfactory = (SessionFactory)context.getBean("sessionFactory");

ChemicalStructureDAO structureDAO = (ChemicalStructureDAO) context.getBean("ChemicalStructureDAO"); 
structureDAO.setSessionFactory(sessionfactory);

ChemicalStructure structure1 = new ChemicalStructure();
structure1.setStructureKey("c1ccccc1");
structure1.setStructureData("c1ccccc1");

structureDAO.create(structure1);

This leads to following error:

Exception in thread "main" org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:941)
at org.bitbucket.myName.moleculedatabaseframework.dao.AbstractHibernateDAO.getCurrentSession(AbstractHibernateDAO.java:78)
at org.bitbucket.myName.moleculedatabaseframework.dao.AbstractHibernateDAO.create(AbstractHibernateDAO.java:54)

I looked at tons of tutorials but they all omit what seems the basic stuff to get things running, eg. ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); does not appear in any spring + hibernate tutorials. Can someone point me at a complete tutorial one that assumes I'm completely dumb and tells me every step required and has an application that actually runs when repeating the code? (yes getting pretty frustrated now. To be honest if I went plain jdbc I would have been up and running hours ago)

Now,how can I get this running? How does autowired work?

EDIT: THE SOLUTION AS FOUND THROUGH THE HELP OF "Accepted Answer":

The new Spring configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
">      


    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" autowire="autodetect">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>org.bitbucket.myName.moleculedatabaseframework.entityclasses.ChemicalStructure</value>
                <value>org.bitbucket.myName.moleculedatabaseframework.entityclasses.ChemicalCompound</value>
                <value>org.bitbucket.myName.moleculedatabaseframework.entityclasses.ChemicalCompoundComposition</value>
            </list>
        </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>
    </bean>     

    <!-- Spring bean configuration. Tell Spring to bounce off BoneCP -->
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
        <property name="targetDataSource">
            <ref local="mainDataSource" />
        </property>
    </bean>

    <!-- BoneCP configuration -->
    <bean id="mainDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
        <property name="driverClass" value="org.postgresql.Driver" />
        <property name="jdbcUrl" value="jdbc:postgresql:MolDB" />
        <property name="username" value="postgres"/>
        <property name="password" value="123456"/>
        <property name="idleConnectionTestPeriod" value="60"/>
        <property name="idleMaxAge" value="240"/>      
        <property name="maxConnectionsPerPartition" value="60"/>
        <property name="minConnectionsPerPartition" value="20"/>
        <property name="partitionCount" value="3"/>
        <property name="acquireIncrement" value="10"/>                              
        <property name="statementsCacheSize" value="50"/>
        <property name="releaseHelperThreads" value="3"/>
    </bean>

    <bean id="txManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:annotation-driven transaction-manager="txManager" />

    <context:annotation-config />

    <bean id="AbstractHibernateDAO" abstract="true"
          class="org.bitbucket.myName.moleculedatabaseframework.dao.AbstractHibernateDAO"/>

    <bean id="ChemicalStructureDAO" parent="AbstractHibernateDAO"
          class="org.bitbucket.myName.moleculedatabaseframework.dao.ChemicalStructureDAO"/>
    <bean id="ChemicalCompoundDAO" parent="AbstractHibernateDAO"
          class="org.bitbucket.myName.moleculedatabaseframework.dao.ChemicalCompoundDAO"/>
</beans>

I had to add

<context:annotation-config />

to the file and declare the annoted entity classes in sessionFactory configuration:

<property name="annotatedClasses">
    <list>
        <value>org.bitbucket.myName.moleculedatabaseframework.entityclasses.ChemicalStructure</value>
        <value>org.bitbucket.myName.moleculedatabaseframework.entityclasses.ChemicalCompound</value>
        <value>org.bitbucket.myName.moleculedatabaseframework.entityclasses.ChemicalCompoundComposition</value>
    </list>
</property>

The I had to uncomment the transaction Manager part and because of that change the data source configuration as the one I used did not work (DataSource is required).

I also had to add

@Repository
@Transactional
public abstract class AbstractHibernateDAO< T extends Serializable> {
    //code...
}

to AbstractHibernateDAO. I'm considering to write a blog post and make a link here. For anyone completley new to Spring and hibernate that would be very useful.

beginner_
  • 7,230
  • 18
  • 70
  • 127

1 Answers1

1

Do you have something like this in your spring xml?

<context:annotation-config />   
<context:component-scan base-package="base.package" />

This scans for the classes that contains Annotations.

sgpalit
  • 2,676
  • 2
  • 16
  • 22
  • solved the issue with autowired. i still get: Exception in thread "main" org.hibernate.HibernateException: No Session found for current thread – beginner_ Oct 05 '12 at 08:37
  • 1
    did you uncommented transactionManager Bean and tx:annotation-driven? txManager should be same with the id of TransactionManager. – sgpalit Oct 05 '12 at 09:01
  • yes. thx. that helped too. After that I ran into several other issues but now I got it working! I'm considering creating a blog post. the full answer is rather too big to put in here. I will mark yoru question as answer and add the updated config to my initial post. – beginner_ Oct 05 '12 at 09:10