InvalidDataAccessApiUsageException: Executing an update/delete query Spring XML to Java config

Viewed 20001

I'm trying to convert spring xml configuration to java configuration. This works perfectly through XML configuration. However, it throws the following exception if I use java config initializer. This happens when it tries to run JQL. The application starts properly though (with all JPA mapping initialized).

org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:410) [spring-orm-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:216) [spring-orm-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417) [spring-orm-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslat

Following is my persistence initializer class. Bit of reading suggested me this is related to transactions are not being started properly. I've put debug points to each of these methods but transactionManager method never gets executed during server startup or any later time. I'm not sure what am I doing wrong :(. Same code based works perfectly when persistence is initialized through persistence.xml.

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "au.mypkg")
public class DatabaseConfig  {


    @Bean(name = "dataSource")
    @Primary
    public DataSource dataSource() throws Exception {
        Context ctx = new InitialContext();
        return (DataSource) ctx.lookup("java:jboss/datasources/mydb");
    }

    @PersistenceContext(unitName = "persistenceUnit")
    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Exception {
    ..........

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        final JtaTransactionManager transactionManager = new JtaTransactionManager();
        transactionManager.setTransactionManagerName(JBOSS_TRANSACTION_MANANGER);
        return transactionManager;
    }

Error occurs when accessing this method on Dao

   public void updateById(final Long id) {

        final String sqlQuery = "UPDATE testtable w SET w.LAST_ACCESSED = :date WHERE w.testtable_ID = :testid";
        final Query query = dao.createNativeQuery(sqlQuery);
        query.setParameter("date", new Date());
        query.setParameter("testid", id);
        query.executeUpdate();
    }
2 Answers
Related