Announcement Announcement Module
Collapse
No announcement yet.
Hibernate JPA not persisting!! Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Hibernate JPA not persisting!!

    Hi all,
    I am trying to use JPA and hibernate for the first time. So, forgive me if this is a silly question. I have a Spring MVC application and I plan to use JPA Hibernate on the DAO layer. I am a connecting to MySQL server.

    With the current code, I am able to do the select operation with no issues at all. But I am not able to persist any new object or make changes to the existing objects.

    Can somebody identify my mistakes? I did search and found post related but, it looks like I have already fixed those issues. Here is my code and configurations:

    persistence.xml :

    Code:
    <persistence-unit name="mypu" transaction-type="RESOURCE_LOCAL">
            <description> Persistence unit for the JPA. </description>
            <provider>org.hibernate.ejb.HibernatePersistence</provider>
    
            <class>aro.samplemvc.domain.Department</class>
    
            <properties>
                <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/jtx"/>
                <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
                <property name="hibernate.connection.username" value="root"/>
                <property name="hibernate.connection.password" value="xxxxx"/>
                <property name="hibernate.show_sql" value="true" />
                <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            </properties>
        </persistence-unit>
    My spring configurations (have removed MVC related as there is no issues with it):

    Code:
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
    
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
              <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
              <property name="url" value="jdbc:mysql://localhost:3306/jtx" />
              <property name="username" value="root"/>
              <property name="password" value="milestone1" />
        </bean>
    
        <tx:annotation-driven transaction-manager="transactionManager" />
    
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="persistenceUnitName" value="mypu"/>
            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
            </property>
        </bean>
    
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory" />
        </bean>
    My Entity:

    Code:
    @Entity
    @Table(name="departments")
    public class Department {
    
        @Id
        @Column(name="id")
        @GeneratedValue(strategy = GenerationType.AUTO)    
        private int id;
        
        @Column(name="dname")
        private String dname;
    
       // methods...
    }
    And my service class:

    Code:
    @Repository
    public class DepartmentDAO implements IDepartmentDAO {
    
        private static final Logger logger = Logger.getLogger(DepartmentDAO.class);
    
        private EntityManager em;
    
        @PersistenceContext
        public void setEm(EntityManager em) {
    
            this.em = em;
        }
    
        @Override
        @Transactional
        public int add(Department dept) {
    
            logger.debug("DepartmentDAO - add() running...");
    
            try {
                em.persist(dept);
                return 0;
            }catch (Exception e) {
                logger.error("DepartmentDAO - add() - Exception : " + e.getMessage());
                logger.error("Stacktrace: " + e.getStackTrace());
                return 500;
            }
            
        }
    
        @Override
        public List<Department> findAll() {
    
            logger.debug("DepartmentDAO - findAll() running... ");
    
            List<Department> result = null;
            try {
    
                result = em.createQuery("select dept from " + Department.class.getName() + " dept").getResultList();
                logger.debug("Result List SIZE: " + result.size());
    
            } catch(Exception e) {
                logger.error("DepartmentDAO - findAll() :  "  + e.getMessage());
                logger.error("Stacktrace : "+ e.getStackTrace());
            }
    
            return result;
        }
    
    }
    I tried placing the @Transactional annotation at class level and also at method level. I also tried to remove it but then I get error about able to start transaction.

    Can somebody point me in right direction?

    Thanks in advance.
    Aro

  • #2
    Don't catch exceptions that breaks proper tx management. Also your datasource is useless as you already configured connection properties in the persistence.xml and you aren't referencing the datasource for your entitymanagerfactory.

    Judging from your code you also use component-scanning to scan for beans. So my guess is you are running into problems from that and that is by scanning the same object twice (leading to duplicate beans one proxied one not proxied for transactions (the latter is probably used by your controllers).

    Comment


    • #3
      Thanks for your reply and Yes, the datasource is useless... I am not using it since its configured through persistence.xml. Can you tell me the best way to avoid scanning the same object twice?
      Last edited by olakara; Dec 28th, 2011, 12:18 AM. Reason: added thanks :)

      Comment


      • #4
        When using component-scanning the contextloaderlistener should scan for everything but @COntroller the dispatcherservlet should scan ONLY for controllers.

        Comment

        Working...
        X