Page 1 of 2 12 LastLast
Results 1 to 10 of 16

Thread: Hibernate + Postgre problem

  1. #1

    Default Hibernate + Postgre problem

    Hi,
    I do not have enough experience with hibernate, so my question is easy.
    I must set the hibernate with postgre database. I have annotations in model classes. Transaction manager, data source and session factory are in the application context. The problem is when I want to receive an object from repository I receive "Exception in thread "main" org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here". Where I must start searching the error?
    My context:
    Code:
    	<tx:annotation-driven transaction-manager="transactionManager" />
    	<bean id="transactionManager"
    		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    		<property name="sessionFactory" ref="sessionFactory" />
    	</bean>
    	<bean id="sessionFactory"
    		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    		<property name="dataSource" ref="dataSource" />
    	</bean>
    
    
    	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    		<property name="driverClassName">
    			<value>org.postgresql.Driver</value>
    		</property>
    		<property name="url">
    			<value>jdbc:postgresql://${url}</value>
    		</property>
    		<property name="username">
    			<value>${user}</value>
    		</property>
    		<property name="password">
    			<value>${pass}</value>
    		</property>
    	</bean>

  2. #2
    Join Date
    Aug 2006
    Location
    Arequipa-Peru / South America
    Posts
    2,796

    Default

    Code:
    "Exception in thread "main" org.hibernate.HibernateException: 
    No Hibernate Session bound to thread, 
    and configuration does not allow creation of non-transactional one here"
    Can you post the complete error stack trace?
    Post your DAO java code, I want to see if you included the @Transactional annotation or if something is missing

    I suggest you read about Spring/Hibernate configuration and specially how configure the dataSource you are not defining many Hibernate properties, it could be a reason

    I suggest you change org.apache.commons.dbcp.BasicDataSource (very simple) to other like com.mchange.v2.c3p0.ComboPooledDataSource, of course when all be solved
    - Manuel Jordan

    Kill Your Pride, Share Your Knowledge With All
    The Fear Of The LORD Is The Beginning Of Knowledge, But Fools Despise Wisdom And Discipline. Proverbs 1:7

    Blog


    Technical Reviewer of Apress

    • Pro SpringSource dm Server
    • Spring Enterprise Recipes: A Problem-Solution Approach
    • Spring Recipes: A Problem-Solution Approach, 2nd Edition
    • Pro Spring Integration
    • Pro Spring Batch
    • Pro Spring 3
    • Pro Spring MVC: With Web Flow
    • Pro Spring Security

  3. #3

    Default

    Thanks for the answer. The error has gone when I changed my DAO.
    DOA class:
    Code:
    package org.mbs.billing.repository.impl;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.mbs.billing.model.PhaseType;
    import org.mbs.billing.repository.PhaseTypeRepository;
    
    public class HibernatePhaseTypeRepository implements PhaseTypeRepository {
    
    	private SessionFactory sessionFactory;
    
    	public HibernatePhaseTypeRepository(SessionFactory sessionFactory) {
    		super();
    		this.sessionFactory = sessionFactory;
    	}
    
    	public PhaseType getByID(int id) {
    		return (PhaseType) getCurrentSession().load(PhaseType.class,
    				Integer.valueOf(id));
    
    	}
    
    	public PhaseType getByName(String name) {
    		return (PhaseType) getCurrentSession().createQuery(
    				"from phase_type where name = :name").setString("name", name)
    				.uniqueResult();
    	}
    
    	protected Session getCurrentSession() {
    		try {
    			return sessionFactory.getCurrentSession();
    		} catch (Exception e) {
    			return sessionFactory.openSession();
    		}
    	}
    
    }
    In the previous version method getCurrentSession has only one line
    Code:
    return sessionFactory.getCurrentSession()
    . Now it works and I can get the data from my Postgre database. What are the advantages of com.mchange.v2.c3p0.ComboPooledDataSource?

  4. #4

    Default

    I have another problem now. Only select statements are sent to database. No insert, update or delete statements can not be executed. There is no error returned, just nothing happens when call them.
    Code:
    <?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:tx="http://www.springframework.org/schema/tx"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans
                  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                  http://www.springframework.org/schema/tx
                  http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                  http://www.springframework.org/schema/context
                  http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    
    	<context:annotation-config />
    	<context:property-placeholder
    		location="C:\\springsource\\core-spring-workspace\\org.mbs.billing\\src\\main\\java\\org\\mbs\\billing\\datasource.properties" />
    
    
    	<tx:annotation-driven transaction-manager="transactionManager" />
    	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    		<property name="driverClassName">
    			<value>org.postgresql.Driver</value>
    		</property>
    		<property name="url">
    			<value>jdbc:postgresql://${url}</value>
    		</property>
    		<property name="username">
    			<value>${user}</value>
    		</property>
    		<property name="password">
    			<value>${pass}</value>
    		</property>
    	</bean>
    
    	<bean id="sessionFactory"
    		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    		<property name="dataSource" ref="dataSource" />
    		<property name="annotatedClasses">
    			<list>
    				<value>org.mbs.billing.model.Phase</value>
    				<value>org.mbs.billing.model.PhaseType</value>
    				<value>org.mbs.billing.model.RoadMap</value>
    			</list>
    		</property>
    		<property name="hibernateProperties">
    			<props>
    				<prop key="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</prop>
    				<prop key="hibernate.show_sql">true</prop>
    				<prop key="hibernate.connection.autocommit">true</prop>
    			</props>
    		</property>
    	</bean>
    
    	<bean id="transactionManager"
    		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    		<property name="sessionFactory" ref="sessionFactory" />
    	</bean>
    	<bean id="phaseRepository"
    		class="org.mbs.billing.repository.impl.HibernatePhaseRepository">
    		<constructor-arg ref="sessionFactory" />
    	</bean>
    	<bean id="phaseTypeRepository"
    		class="org.mbs.billing.repository.impl.HibernatePhaseTypeRepository">
    		<constructor-arg ref="sessionFactory" />
    	</bean>
    	<bean id="roadMapRepository"
    		class="org.mbs.billing.repository.impl.HibernateRoadMapRepository">
    		<constructor-arg ref="sessionFactory" />
    	</bean>
    
    </beans>
    One of the DAO
    Code:
    package org.mbs.billing.repository.impl;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.mbs.billing.model.PhaseType;
    import org.mbs.billing.repository.PhaseTypeRepository;
    
    public class HibernatePhaseTypeRepository implements PhaseTypeRepository {
    
    	private SessionFactory sessionFactory;
    
    	public HibernatePhaseTypeRepository(SessionFactory sessionFactory) {
    		super();
    		this.sessionFactory = sessionFactory;
    	}
    
    	public PhaseType getByID(int id) {
    		return (PhaseType) getCurrentSession().load(PhaseType.class,
    				Integer.valueOf(id));
    
    	}
    
    	public PhaseType getByName(String name) {
    		return (PhaseType) getCurrentSession().createQuery(
    				"from phase_type where name = :name").setString("name", name)
    				.uniqueResult();
    	}
    
    	protected Session getCurrentSession() {
    		try {
    			return sessionFactory.getCurrentSession();
    		} catch (Exception e) {
    			return sessionFactory.openSession();
    		}
    	}
    
    	public void delete(int id) {
    		PhaseType phaseType = (PhaseType)getCurrentSession().load(PhaseType.class, id);
    		getCurrentSession().delete(phaseType);
    		
    	}
    
    	public void store(PhaseType phaseType) {
    		getCurrentSession().saveOrUpdate(phaseType);		
    	}
    
    }
    THis code I try to run
    Code:
    	public static void main(String[] args) {
    		
    		ApplicationContext ctx = new FileSystemXmlApplicationContext(
            "C:\\springsource\\core-spring-workspace\\org.mbs.billing\\src\\main\\java\\org\\mbs\\billing\\context.xml");
    		
    		PhaseRepository o = (HibernatePhaseRepository)ctx.getBean("phaseRepository");
    		PhaseTypeRepository o1 = (PhaseTypeRepository)ctx.getBean("phaseTypeRepository");
    		PhaseType p = new PhaseType();
    		p.setName("test");
    		p.setId(2);
    		o1.store(p);
    		o1.delete(1);
    	}
    This the console output
    Code:
    log4j:WARN Continuable parsing error 42 and column 23
    log4j:WARN The content of element type "log4j:configuration" must match "(renderer*,appender*,(category|logger)*,root?,categoryFactory?)".
    INFO : org.springframework.context.support.FileSystemXmlApplicationContext - Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@fd68b1: display name [org.springframework.context.support.FileSystemXmlApplicationContext@fd68b1]; startup date [Sun Oct 31 11:21:17 EET 2010]; root of context hierarchy
    INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from file [C:\springsource\core-spring-workspace\org.mbs.billing\src\main\java\org\mbs\billing\context.xml]
    INFO : org.springframework.context.support.FileSystemXmlApplicationContext - Bean factory for application context [org.springframework.context.support.FileSystemXmlApplicationContext@fd68b1]: org.springframework.beans.factory.support.DefaultListableBeanFactory@137d090
    INFO : org.springframework.beans.factory.config.PropertyPlaceholderConfigurer - Loading properties file from file [C:\springsource\core-spring-workspace\org.mbs.billing\src\main\java\org\mbs\billing\datasource.properties]
    INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@137d090: defining beans [org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,dataSource,sessionFactory,transactionManager,phaseRepository,phaseTypeRepository,roadMapRepository]; root of factory hierarchy
    Hibernate: select phasetype0_.ID as ID1_0_, phasetype0_.NAME as NAME1_0_ from mbs.phase_type phasetype0_ where phasetype0_.ID=?
    Is this happens because of transactions ot something else?
    Last edited by Alexandr.Kormiltsyn; Oct 31st, 2010 at 04:31 AM.

  5. #5
    Join Date
    Aug 2006
    Location
    Arequipa-Peru / South America
    Posts
    2,796

    Default

    Hello

    . Now it works and I can get the data from my Postgre database. What are the advantages of com.mchange.v2.c3p0.ComboPooledDataSource?
    BasicDataSource is basic, no pool support, not recommended for production, instead ComboPooledDataSource can handle pools

    Remove this line <prop key="hibernate.connection.autocommit">true</prop> try again to execute the code

    No insert, update or delete statements can not be executed. There is no error returned, just nothing happens when call them.
    after to remove the indicated line, if no DB CRUD operation happen
    replace saveOrUpdate(phaseType); by using save() and update() explicitly

    Let me know your advance
    - Manuel Jordan

    Kill Your Pride, Share Your Knowledge With All
    The Fear Of The LORD Is The Beginning Of Knowledge, But Fools Despise Wisdom And Discipline. Proverbs 1:7

    Blog


    Technical Reviewer of Apress

    • Pro SpringSource dm Server
    • Spring Enterprise Recipes: A Problem-Solution Approach
    • Spring Recipes: A Problem-Solution Approach, 2nd Edition
    • Pro Spring Integration
    • Pro Spring Batch
    • Pro Spring 3
    • Pro Spring MVC: With Web Flow
    • Pro Spring Security

  6. #6

    Default

    I removed the line with autocimmit. Tried to delete record from db.
    My context now:
    Code:
    <?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:tx="http://www.springframework.org/schema/tx"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
    
    
    	<bean id="transactionManager"
    		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    		<property name="sessionFactory" ref="sessionFactory" />
    	</bean>
    	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    		<property name="driverClassName">
    			<value>org.postgresql.Driver</value>
    		</property>
    		<property name="url">
    			<value>jdbc:postgresql://${url}</value>
    		</property>
    		<property name="username">
    			<value>${user}</value>
    		</property>
    		<property name="password">
    			<value>${pass}</value>
    		</property>
    	</bean>
    	<bean id="sessionFactory"
    		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    		<property name="dataSource" ref="dataSource" />
    		<property name="annotatedClasses">
    			<list>
    				<value>org.mbs.billing.model.Phase</value>
    				<value>org.mbs.billing.model.PhaseType</value>
    				<value>org.mbs.billing.model.RoadMap</value>
    			</list>
    		</property>
    		<property name="hibernateProperties">
    			<props>
    				<prop key="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</prop>
    				<prop key="hibernate.show_sql">true</prop>
    			</props>
    		</property>
    	</bean>
    	<bean id="phaseRepository"
    		class="org.mbs.billing.repository.impl.HibernatePhaseRepository">
    		<constructor-arg ref="sessionFactory" />
    	</bean>
    	<bean id="phaseTypeRepository"
    		class="org.mbs.billing.repository.impl.HibernatePhaseTypeRepository">
    		<constructor-arg ref="sessionFactory" />
    	</bean>
    	<bean id="roadMapRepository"
    		class="org.mbs.billing.repository.impl.HibernateRoadMapRepository">
    		<constructor-arg ref="sessionFactory" />
    	</bean>
    </beans>
    DAO:
    Code:
    package org.mbs.billing.repository.impl;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.mbs.billing.model.PhaseType;
    import org.mbs.billing.repository.PhaseTypeRepository;
    
    public class HibernatePhaseTypeRepository implements PhaseTypeRepository {
    
    	private SessionFactory sessionFactory;
    	
    	public PhaseType getByID(int id) {
    		return (PhaseType) getCurrentSession().load(PhaseType.class,
    				Integer.valueOf(id));
    
    	}
    
    	public HibernatePhaseTypeRepository(SessionFactory sessionFactory) {
    		super();
    		this.sessionFactory = sessionFactory;
    	}
    
    	public PhaseType getByName(String name) {
    		return (PhaseType) getCurrentSession().createQuery(
    				"from phase_type where name = :name").setString("name", name)
    				.uniqueResult();
    	}
    
    	protected Session getCurrentSession() {
    		try {
    			return sessionFactory.getCurrentSession();
    		} catch (Exception e) {
    			return sessionFactory.openSession();
    		}
    	}
    
    	public void delete(int id) {
    		PhaseType phaseType = (PhaseType)getCurrentSession().load(PhaseType.class, id);
    		getCurrentSession().delete(phaseType);
    		
    	}
    
    	public void store(PhaseType phaseType) {
    		getCurrentSession().saveOrUpdate(phaseType);		
    	}
    
    }
    Executing code:
    Code:
    	public static void main(String[] args) {
    		ApplicationContext ctx = new FileSystemXmlApplicationContext(
    				"C:\\springsource\\core-spring-workspace\\org.mbs.billing\\src\\main\\java\\org\\mbs\\billing\\context.xml");
    		PhaseTypeRepository rep = (PhaseTypeRepository) ctx
    				.getBean("phaseTypeRepository");
    		PhaseType pt = rep.getByID(1);
    		System.out.println(pt.toString());
    		rep.delete(1);
    	}
    Console out:
    Code:
    log4j:WARN Continuable parsing error 42 and column 23
    log4j:WARN The content of element type "log4j:configuration" must match "(renderer*,appender*,(category|logger)*,root?,categoryFactory?)".
    INFO : org.springframework.context.support.FileSystemXmlApplicationContext - Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@cbf30e: display name [org.springframework.context.support.FileSystemXmlApplicationContext@cbf30e]; startup date [Mon Nov 01 00:25:26 EET 2010]; root of context hierarchy
    INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from file [C:\springsource\core-spring-workspace\org.mbs.billing\src\main\java\org\mbs\billing\context.xml]
    INFO : org.springframework.context.support.FileSystemXmlApplicationContext - Bean factory for application context [org.springframework.context.support.FileSystemXmlApplicationContext@cbf30e]: org.springframework.beans.factory.support.DefaultListableBeanFactory@1884174
    INFO : org.springframework.beans.factory.config.PropertyPlaceholderConfigurer - Loading properties file from file [C:\springsource\core-spring-workspace\org.mbs.billing\src\main\java\org\mbs\billing\datasource.properties]
    INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1884174: defining beans [org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,dataSource,sessionFactory,transactionManager,phaseRepository,phaseTypeRepository,roadMapRepository]; root of factory hierarchy
    Hibernate: select phasetype0_.ID as ID1_0_, phasetype0_.NAME as NAME1_0_ from mbs.PHASE_TYPE phasetype0_ where phasetype0_.ID=?
    PhaseType [id=1, name=test]
    Hibernate: select phasetype0_.ID as ID1_0_, phasetype0_.NAME as NAME1_0_ from mbs.PHASE_TYPE phasetype0_ where phasetype0_.ID=?
    Would you be so kind to help me with this problem?

  7. #7
    Join Date
    Aug 2006
    Location
    Arequipa-Peru / South America
    Posts
    2,796

    Default

    Wait a minute

    Why here

    Code:
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    		<property name="driverClassName">
    			<value>org.postgresql.Driver</value>
    		</property>
    and here

    Code:
    	
    <bean id="sessionFactory"
             class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    ...
    	<property name="hibernateProperties">
    	   <props>
    		<prop key="hibernate.dialect">                     
                                    org.hibernate.dialect.HSQLDialect
                           </prop>
    		<prop key="hibernate.show_sql">true</prop>
     	   </props>
    	</property>
    </bean>
    Postqresql with HSQLDialect?
    Fix this and let me know what happen now
    - Manuel Jordan

    Kill Your Pride, Share Your Knowledge With All
    The Fear Of The LORD Is The Beginning Of Knowledge, But Fools Despise Wisdom And Discipline. Proverbs 1:7

    Blog


    Technical Reviewer of Apress

    • Pro SpringSource dm Server
    • Spring Enterprise Recipes: A Problem-Solution Approach
    • Spring Recipes: A Problem-Solution Approach, 2nd Edition
    • Pro Spring Integration
    • Pro Spring Batch
    • Pro Spring 3
    • Pro Spring MVC: With Web Flow
    • Pro Spring Security

  8. #8

    Default

    I have changed dialect to
    Code:
    				<prop key="hibernate.dialect">                     
                                    org.hibernate.dialect.PostgreSQLDialect
                     </prop>
    But nothing changed. Also, I debugged DAO and noticed that this method
    Code:
    	protected Session getCurrentSession() {
    		try {
    			return sessionFactory.getCurrentSession();
    		} catch (Exception e) {
    			return sessionFactory.openSession();
    		}
    	}
    always throws exception and actually every time openSession() is called. May be this is a problem with transactions?

  9. #9

    Default

    Finally I have found a solution. I have added @Transactional annotations to DAO and rewrited getCurrentSession method as follows:
    Code:
    	protected Session getCurrentSession() {
    		return sessionFactory.getCurrentSession();
    	}
    Also, I chaged my getByID method as follows:
    Code:
    @Transactional(readOnly = true)
    	public PhaseType getByID(int id) {
    		return (PhaseType) getCurrentSession().get(PhaseType.class,
    				Integer.valueOf(id));
    
    	}
    Actually I replaced load with get.
    Also there is another problem with sequence usage in hibernate. Is it correct, when hibernate generates such an SQL?
    Code:
    Hibernate: call next value for mbs.phase_type_seq
    WARN : org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 42601
    ERROR: org.hibernate.util.JDBCExceptionReporter - ERROR: syntax error at or near "call"

  10. #10
    Join Date
    Aug 2006
    Location
    Arequipa-Peru / South America
    Posts
    2,796

    Default

    Alexandr

    Finally I have found a solution. I have added @Transactional annotations to DAO and rewrited getCurrentSession method as follows:
    I suggest you read carefully the Spring documentation about Spring+Hibernate integration, let Spring manage the Hibernate's Session

    Of course, is good have @Transactional annotations in the DAO methods

    Actually I replaced load with get.
    Better is use get instead of load, more information about the difference between here 11.3. Loading an object

    Also there is another problem with sequence usage in hibernate. Is it correct, when hibernate generates such an SQL?
    Again, read Hibernate configuration about how configure this correctly
    - Manuel Jordan

    Kill Your Pride, Share Your Knowledge With All
    The Fear Of The LORD Is The Beginning Of Knowledge, But Fools Despise Wisdom And Discipline. Proverbs 1:7

    Blog


    Technical Reviewer of Apress

    • Pro SpringSource dm Server
    • Spring Enterprise Recipes: A Problem-Solution Approach
    • Spring Recipes: A Problem-Solution Approach, 2nd Edition
    • Pro Spring Integration
    • Pro Spring Batch
    • Pro Spring 3
    • Pro Spring MVC: With Web Flow
    • Pro Spring Security

Posting Permissions

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