0

I am getting the below error, I have gone through all of the similar issues, but don't able to figure out where I am going wrong.

Here is the error:

Exception in thread "main" javax.persistence.TransactionRequiredException: No transactional EntityManager available
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:275)
    at com.sun.proxy.$Proxy19.persist(Unknown Source)
    at com.project.vibhas.dao.hibernate.GenericDaoJpa.save(GenericDaoJpa.java:45)
    at com.project.vibhas.service.impl.PersonServiceImpl.save(PersonServiceImpl.java:22)
    at com.project.vibhas.domain.App.main(App.java:25)

Here are my code:

package com.project.vibhas.dao.hibernate;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
import com.project.vibhas.dao.GenericDao;
import com.project.vibhas.domain.DomainObject;

public class GenericDaoJpa<T extends DomainObject> implements GenericDao<T> {
    private Class<T> type;
    protected EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public GenericDaoJpa(Class<T> type) {
        super();
        this.type = type;
    }


    @Transactional
    public void save(T object) {
        System.out.println("inside generic dao");
            entityManager.persist(object);
    }

    public void delete(T object) {
        entityManager.remove(object);
    }
}

My Dao class:

@Repository("personDao")
public class PersonDaoJpa extends GenericDaoJpa<Person> implements PersonDao {
    public PersonDaoJpa() {
        super(Person.class);
    }

    public Person authenticatePerson(String username, String password)
            throws DataAccessException, AuthenticationException {
        List<Person> results = null;
        Query query = entityManager
                .createQuery("from Person as p where p.username = :username and p.password = :password");
        query.setParameter("username", username);
        query.setParameter("password", password);
        results = query.getResultList();
        if (results == null || results.size() <= 0) {
            throw new AuthenticationException("No users found");
        } else {
            return results.get(0);
        }
    }

    public Person getPersonByUsername(String username)
            throws DataAccessException, EntityNotFoundException {
        List<Person> results = null;
        Query query = entityManager
                .createQuery("from Person as p where p.username = :username");
        query.setParameter("username", username);
        results = query.getResultList();
        if (results == null || results.size() <= 0) {
            throw new EntityNotFoundException(username + " not found");
        } else {
            return results.get(0);
        }
    }
}

My sercice Class:

package com.project.vibhas.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.project.vibhas.dao.PersonDao;
import com.project.vibhas.domain.Person;
import com.project.vibhas.service.PersonService;

@Service("personService")
public class PersonServiceImpl implements PersonService{

    @Autowired
    PersonDao personDao;

    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }
    public void save(Person person) {
        System.out.println("Inside service");
        //personDao.get(1L);
        personDao.save(person);

    }

}

My Test Class:

package com.project.vibhas.domain;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.project.vibhas.service.PersonService;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext appContext = new ClassPathXmlApplicationContext(
                "classpath*:META-INF/spring/spring-jpa.xml");

        PersonService personService = (PersonService) appContext.getBean("personService");


        Person person = new Person();
        person.setId(1L);

        personService.save(person);

        System.out.println("Done");
    }
}

Spring-Jpa.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <!-- The rest of the config is covered below -->

    <context:annotation-config />
    <context:spring-configured />

     <context:component-scan base-package="com.project" />


    <bean id="dataSource" 
       class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" 
        p:driverClassName="org.postgresql.Driver"
        p:url="jdbc:postgresql://localhost:5433/mypostgresdb" 
        p:username="postgres"
        p:password="root" />

    <bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource"/>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
        p:entityManagerFactory-ref="entityManagerFactory" />

    <tx:annotation-driven mode="aspectj"
        transaction-manager="transactionManager" />

</beans>

Persistence.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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_2_0.xsd"
version="2.0">
<persistence-unit name="galleryPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>


<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<!--
value='create' to build a new database on each run;
value='update' to modify an existing database;
value='create-drop' to create and drop tables on each run;
value='validate' makes no changes to the database
-->
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="true"/>
</properties>

</persistence-unit>
</persistence>
vibhas
  • 1,449
  • 4
  • 18
  • 32
  • duplicate? http://stackoverflow.com/questions/22382950/no-transactional-entitymanager-available-working-with-jpa-api-error-with-hibe – user993553 Oct 18 '15 at 10:45
  • But the solution is not fitting to my situation as I am using the correct @transaction from springframework – vibhas Oct 18 '15 at 11:03
  • 1
    Have you read the following from the documentation? *The alternative mode "aspectj" instead weaves the affected classes with Spring’s AspectJ transaction aspect, modifying the target class byte code to apply to any kind of method call. AspectJ weaving requires spring-aspects.jar in the classpath as well as load-time weaving (or compile-time weaving) enabled. (See the section called “Spring configuration” for details on how to set up load-time weaving.)*: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#tx-annotation-driven-settings – JB Nizet Oct 18 '15 at 11:20

0 Answers0