Results 1 to 9 of 9

Thread: Data not inserting into Database - JPA+Spring+Hibernate

  1. #1

    Default Data not inserting into Database - JPA+Spring+Hibernate

    Hi All,

    I am working with a small sample application using Spring+JPA+Hibernate+HSQLDB. (New Starter for JPA)

    I am facing a peculiar problem with this. When i tried to persists my POJO, i am not able to do that in the database. And i am not getting any error also.

    My application code base is as follows:-

    POJO

    Code:
    import java.util.List;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;
    @Entity
    @Table(name="Role")
    public class Role {
    	 @Id
         @GeneratedValue(strategy=GenerationType.SEQUENCE)     
                private long roleID;			
                private String name;
    	private String description;
    	private boolean hasAccessLevel;	
    }
    (Removed getter/setter for code brevity)

    my DAO and DAO IMPl is as follows

    Code:
    public interface RoleDAO extends BaseDAO {	
    	public Role findById(long roleID);	
    	public Role findByName(String roleName);	
    	public Role findByDescription(String description);	
    	public List <Role> findAllRoles();
    }
    
    public class RoleDAOImpl implements RoleDAO {
    JpaTemplate jpaTemplate;
    	public void saveObject(Object obj) {
    		// TODO Auto-generated method stub
    		jpaTemplate.persist(obj);
    		
    	}
    public void setJpaTemplate(JpaTemplate jpaTemplate)
    	{
    		this.jpaTemplate=jpaTemplate;
    		
    	}
    (shown only one method- that i am using )

    configuration file is as follows

    persistence.xml

    Code:
    <?xml version="1.0" encoding="UTF-8"?> 
    <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> 
    
      <persistence-unit name="RTECApp" transaction-type="RESOURCE_LOCAL">     
     <provider>org.hibernate.ejb.HibernatePersistence</provider>    <class>com.mori.rcc.architecture.framework.persistence.entities.Role</class>
    <properties>
                <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
    			<property name="hibernate.hbm2ddl.auto" value="create-update"/>
    	</properties>
    </persistence-unit>   
    </persistence>
    applicationContext.xml

    Code:
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean ">
           <property name="persistenceUnitName" value="RTECApp"/>
           <property name="dataSource" ref="dataSource"/>
           <!--
           <property name="loadTimeWeaver">
    		<bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver"/>
    		</property>       -->
           <!-- <property name="loadTimeWeaver" class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/> -->
           <property name="jpaVendorAdapter" ref="vendorAdapter"/>
        </bean> 
    
    	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
           <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
    		  <property name="url" value="jdbc:hsqldb:hsql://localhost"/>
    		  <property name="username" value="sa"/>
    		  <property name="password" value=""/>
        </bean> 
    	
    	<bean id="vendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">       
    	<property name="generateDdl" value="true"/>
    	<property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
    		<!-- <property name="database" value="HSQL" />	
           <property name="showSql" value="true"/>
           <property name="generateDdl" value="true"/> -->
        </bean> 
    	
    	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
           <property name="entityManagerFactory" ref="entityManagerFactory"/>
           <property name="dataSource" ref="dataSource"/>
        </bean> 
    	
    		<bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate">
    		<property name="entityManagerFactory">
    			<ref bean="entityManagerFactory" />
    		</property>
    	</bean>
    	
    	 <bean name="roleDAO" class="com.mori.rcc.architecture.framework.persistence.dao.impl.RoleDAOImpl">
    		<property name="jpaTemplate">
    			<ref bean="jpaTemplate" />
    		</property>		
    	</bean>            
    	
    	<bean class="com.mori.rcc.architecture.framework.persistence.entities.Role"/> 
    	
    	<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
    		<property name="entityManagerFactory" ref="entityManagerFactory"/>
    	</bean>
    	
    	<!-- JPA annotations bean post processor -->
    	<bean class="org.springframework.orm.jpa.support.PersistenceAnn otationBeanPostProcessor"/>
    i am not getting any error, even i can able to see the change in sequence too, but no record is inserted into the table.

    can anybody help me out in this ? I am missing something out here ???

    cheers
    sai

  2. #2
    Join Date
    May 2007
    Posts
    5

    Default

    Where are configuring your sequence name....

  3. #3
    Join Date
    Dec 2007
    Posts
    11

    Default Flush

    Did you flush it in the code?

  4. #4
    Join Date
    Mar 2008
    Posts
    5

    Default I have the similar problem

    I'm using postgresql 8.2.6 + Spring 2.5.1 + Hibernate 3.3.2 + JPA .
    no error and no data saved.

    but when I move to mysql (InnoDB) , everything is ok.

    and there're so many similar theads here about data not saved problem through JPA.

    need someone to help us

    applicationContext.xml:
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!--
        Application context definition for PetClinic on JPA.
    -->
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
            xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
            xmlns:tx="http://www.springframework.org/schema/tx"
            xsi:schemaLocation="
                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    
        <context:property-placeholder location="classpath:jdbc-postgresql.properties"/>
    
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
                p:driverClassName="${jdbc.driverClassName}" 
                p:url="${jdbc.url}" 
                p:username="${jdbc.username}"
                p:password="${jdbc.password}"/>
         
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
                p:dataSource-ref="dataSource">
            <property name="persistenceUnitName" value="sfcpu"/>
            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
                        p:database="${jpa.database}" 
                        p:showSql="${jpa.showSql}" 
                        p:generateDdl="true"/>
            </property>
        </bean>
    
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory"/>
            <property name="dataSource" ref="dataSource"/>
        </bean>
        
        <context:annotation-config />
    
        <context:component-scan base-package="com.emice.sfc.service" />
    
        <!--
            Post-processor to perform exception translation on @Repository classes (from native
            exceptions such as JPA PersistenceExceptions to Spring's DataAccessException hierarchy).
        <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
        -->
        
        <tx:annotation-driven transaction-manager="transactionManager" />
        
        <bean id="personAction" scope="prototype" class="com.emice.sfc.sample.PersonAction"> 
        </bean>
        
    	<bean id="userAction" scope="prototype" class="com.emice.sfc.user.UserAction">
        </bean>
    </beans>
    persistence.xml
    Code:
    <?xml version="1.0" encoding="UTF-8"?> 
    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
        version="1.0">
        <persistence-unit name="sfcpu">
            <provider>org.hibernate.ejb.HibernatePersistence</provider>
        </persistence-unit>
    </persistence>
    jdbc-postgresql.properties:
    Code:
    hibernate.generate_statistics = true
    hibernate.show_sql            = true
    jpa.showSql                   = true
    jdbc.driverClassName=org.postgresql.Driver
    jdbc.url=jdbc:postgresql://localhost/quickstart
    jdbc.username=postgres
    jdbc.password=123
    hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
    jpa.database = POSTGRESQL
    Organization.java
    Code:
    package com.emice.sfc.model;
    import javax.persistence.*;
    ...
    @Entity
    @Table(name=Constant.DB_PREFIX+"organizations")
    public class Organization implements IDEntity{
        @Id
        @GeneratedValue
        private Integer id;     
        ...
        @OneToMany(mappedBy="organization",fetch=FetchType.LAZY)
        @OrderBy("id desc")
        private List<Person> people;  
    
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        ... other getter/setter s
    }
    PersistenceServiceImpl.java
    Code:
    package com.emice.sfc.service;
    @Repository
    public class PersistenceServiceImpl implements PersistenceService {
        private EntityManager em;
        @PersistenceContext
        public void setEntityManager(EntityManager em) {
            this.em = em;
        }
        private EntityManager getEntityManager() {
            return em;
        }
        ...
        @Transactional
        public <T extends IDEntity> void save(T obj){
            if (obj.getId() == null) {
                // new
                em.persist(obj);
            } else {
                // update
                em.merge(obj);
            }
        }
    }
    PersistenceServiceTest.java
    Code:
    public class PersistenceServiceTest extends ServiceTestBase{    
        @Autowired
        private PersistenceService ps;
        @Test
        @Transactional
        public void testDeleteEmployeeCascade() {
            Organization org = new Organization();
            org.setEname("emice2");
            ps.save(org);
        }
    }
    I can see insert sql statement in console, and sequence increases too,
    but the table is still empty.
    why ? where's the problem ?
    Thank you !

  5. #5
    Join Date
    Mar 2008
    Posts
    5

    Default faint. it auto rolls back in test context, now it works.

    now I set the defaultRollback to false, data is saved.

    Code:
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "/applicationContext.xml" })
    @Transactional
    @TransactionConfiguration(defaultRollback=false)
    public abstract class ServiceTestBase extends AbstractJpaTests{
        
    }
    sorry for my mistake, I did not open the log4j to see the detail info, in fact it points out when it rolls back.


    but now the question is : why mysql did not rollback automatically in test context ?

  6. #6
    Join Date
    Mar 2008
    Posts
    5

    Smile oh, it's caused by mysql's default db type

    after adding
    Code:
    default-table-type=innodb
    to mysql's config file : my.cnf
    it works fine.

    Great!
    Although it's the first time I using spring, now it seems very charming.


  7. #7
    Join Date
    Mar 2008
    Posts
    5

    Smile

    maybe you can send your code to me : outersky at gmail dot com .
    I'm learning spring and hibernate too .

    Quote Originally Posted by saikiran View Post
    Hi All,

    I am working with a small sample application using Spring+JPA+Hibernate+HSQLDB. (New Starter for JPA)

    I am facing a peculiar problem with this. When i tried to persists my POJO, i am not able to do that in the database. And i am not getting any error also.

    My application code base is as follows:-

    can anybody help me out in this ? I am missing something out here ???

    cheers
    sai

  8. #8

    Default

    Where does the annotation "@TransactionConfiguration(defaultRollback=false)" come from ?

    I searched at spring 2.5.5 and Java EE 5, but could not find.

  9. #9
    Join Date
    Dec 2012
    Posts
    1

    Default

    @TransactionConfiguration is in the spring-test jars

    Code:
    	        <dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-test</artifactId>
    			<version>2.5</version>
    		</dependency>

Posting Permissions

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