Error "Transaction is required to perform this Operation" when inserting, editing, or deleting - Wildfly

Asked

Viewed 5,323 times

2

So, guys, I’ve been racking my brain about this mistake for a while and I can’t figure out how to fix... The situation is this, I had this project running on Tomcat and now it was necessary to migrate to Wildfly, the migration apparently was ok, it is a project in jsf, with cdi, Hibernate and using Maven, I made the necessary changes to . pom and other dependencies and it is logging into the project and the listings are working normal, but at the time of inserting, editing or deleting is giving the error below:

4,913 WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle] (default task-45) #{back.salvar}: javax.persistence.TransactionRequiredException: JBAS011469: Transaction is required to perform this operation (either use a transaction or extended persistence context): javax.faces.FacesException: #{back.salvar}: javax.persistence.TransactionRequiredException: JBAS011469: Transaction is required to perform this operation (either use a transaction or extended persistence context)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118) [jsf-impl-2.2.6-jbossorg-4.jar:]
at javax.faces.component.UICommand.broadcast(UICommand.java:315) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) [jsf-impl-2.2.6-jbossorg-4.jar:]
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.2.6-jbossorg-4.jar:]
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198) [jsf-impl-2.2.6-jbossorg-4.jar:]
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:113) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:56) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:61) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:240) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:227) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:73) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:146) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:177) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:727) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [rt.jar:1.7.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [rt.jar:1.7.0_45]
at java.lang.Thread.run(Unknown Source) [rt.jar:1.7.0_45]
Caused by: javax.faces.el.EvaluationException: javax.persistence.TransactionRequiredException: JBAS011469: Transaction is required to perform this operation (either use a transaction or extended persistence context)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) [jsf-impl-2.2.6-jbossorg-4.jar:]
... 33 more
Caused by: javax.persistence.TransactionRequiredException: JBAS011469: Transaction is required to perform this operation (either use a transaction or extended persistence context)
at org.jboss.as.jpa.container.AbstractEntityManager.transactionIsRequired(AbstractEntityManager.java:867) [wildfly-jpa-8.1.0.Final.jar:8.1.0.Final]
at org.jboss.as.jpa.container.AbstractEntityManager.persist(AbstractEntityManager.java:580) [wildfly-jpa-8.1.0.Final.jar:8.1.0.Final]
at com.inbit.projetobase.view.back.RecursoBack.salvar(RecursoBack.java:34) [classes:]
at com.inbit.projetobase.view.back.RecursoBack$Proxy$_$$_WeldClientProxy.salvar(Unknown Source) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.7.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.7.0_45]
at java.lang.reflect.Method.invoke(Unknown Source) [rt.jar:1.7.0_45]
at com.sun.el.parser.AstValue.invoke(AstValue.java:275) [javax.el-3.0.0.jar:]
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304) [javax.el-3.0.0.jar:]
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) [jsf-impl-2.2.6-jbossorg-4.jar:]
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
... 34 more

09:24:54,919 INFO  [stdout] (default task-45) 2014-09-16 09:24:54 ERROR context:218 - javax.faces.el.EvaluationException: javax.persistence.TransactionRequiredException: JBAS011469: Transaction is required to perform this operation (either use a transaction or extended persistence context)

09:24:54,919 INFO  [stdout] (default task-45)   at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)

09:24:54,919 INFO  [stdout] (default task-45)   at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)

09:24:54,919 INFO  [stdout] (default task-45)   at javax.faces.component.UICommand.broadcast(UICommand.java:315)

09:24:54,919 INFO  [stdout] (default task-45)   at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)

09:24:54,919 INFO  [stdout] (default task-45)   at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)

09:24:54,920 INFO  [stdout] (default task-45)   at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)

09:24:54,920 INFO  [stdout] (default task-45)   at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)

09:24:54,920 INFO  [stdout] (default task-45)   at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)

09:24:54,920 INFO  [stdout] (default task-45)   at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)

09:24:54,920 INFO  [stdout] (default task-45)   at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)

09:24:54,920 INFO  [stdout] (default task-45)   at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61)

09:24:54,920 INFO  [stdout] (default task-45)   at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)

09:24:54,920 INFO  [stdout] (default task-45)   at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)

09:24:54,920 INFO  [stdout] (default task-45)   at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25)

09:24:54,921 INFO  [stdout] (default task-45)   at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:113)

09:24:54,921 INFO  [stdout] (default task-45)   at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:56)

09:24:54,921 INFO  [stdout] (default task-45)   at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25)

09:24:54,921 INFO  [stdout] (default task-45)   at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45)

09:24:54,921 INFO  [stdout] (default task-45)   at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:61)

09:24:54,921 INFO  [stdout] (default task-45)   at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58)

09:24:54,925 INFO  [stdout] (default task-45)   ... 34 more

09:24:54,925 INFO  [stdout] (default task-45) 

Remembering that before, when I used to ride the Tomcat I "took care" of the entityManager, as follows:

@DataRepository
@Inject
protected EntityManager entityManager;

And now Wildfly would take care of it for me, right? I started using:

@PersistenceContext(name="pu", type=PersistenceContextType.EXTENDED)
protected EntityManager entityManager;

Would anyone know what I’m doing wrong? I’ve always worked with Tomcat and it’s the first time I’ve ever migrated a project to Wildfly, and I can’t identify which mistake I’m making... I’ve tried @Statefull and @Stateless on Cruddao but without success(I must have used it wrong)

It follows the classes I’m using: Cruddao:

@Named("crudDAO")
public class CrudDAO<E> implements Serializable {

private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(CrudDAO.class);

@PersistenceContext(name="pu", type=PersistenceContextType.EXTENDED)
protected EntityManager entityManager;

public CrudDAO() {
    super();
}

public void cadastrar(E entidade) {
    entityManager.persist(entidade);
}

public void atualizar(E entidade) {
    entityManager.merge(entidade);
}

public void deletar(E entidade) {
    entityManager.remove(entidade);
    entityManager.flush();;
}

public E buscarPorId(Class<E> clazz, Object id) {
    return entityManager.find(clazz, id);
}

@SuppressWarnings("unchecked")
public List<E> listar(Class<E> clazz) {
    List<E> lista = new ArrayList<E>();
    lista = entityManager.createQuery(" FROM " + clazz.getName())
            .getResultList();
    return lista;
}

@SuppressWarnings("unchecked")
public List<E> listarAtivos(Class<E> clazz) {
    List<E> lista = new ArrayList<E>();
    String hql = " FROM " + clazz.getName() + " WHERE ativo = :ativo";
    Query q = entityManager.createQuery(hql);
    q.setParameter("ativo", true);
    lista = q.getResultList();
    return lista;
}

public int total(E pesquisa) {
    Long count = 0L;

    try {
        Query q = entityManager.createQuery("SELECT count(*) FROM "
                + pesquisa.getClass().getName());
        count = (Long) q.getSingleResult();
    } catch (Exception e) {
        LOGGER.error("Erro ao buscar total listagem lazy", e);
    }
    return count.intValue();
}

@SuppressWarnings("unchecked")
public List<E> listarLazy(E pesquisa, int startingAt, int maxPerPage,
        String sortField, String sortOrder) {
    List<E> lista = new ArrayList<E>();
    try {
        Query q = entityManager.createQuery("FROM "
                + pesquisa.getClass().getName());
        q.setFirstResult(startingAt);
        q.setMaxResults(maxPerPage);
        lista = q.getResultList();
    } catch (Exception e) {
        LOGGER.error("Erro ao buscar listagem Lazy", e);
    }
    return lista;
}

}

Cross:

@Named("crudBO")
public class CrudBO<E extends BaseEntity> implements Serializable{

private static final long serialVersionUID = 1L;

@Inject
@Named("crudDAO")
protected CrudDAO<E> dao;

private static final Logger LOGGER = Logger.getLogger(CrudBO.class);

public CrudBO() {
    super();
}

public CrudBO(CrudDAO<E> dao) {
    super();
    this.dao = dao;
}

public String salvar(E entidade) {
    if (registroJaExiste(entidade)) {
        dao.atualizar(entidade);
        return "Editado com sucesso!";
    } else {
        dao.cadastrar(entidade);
        return "Cadastrado com sucesso!";
    }
}

public String deletar(E entidade) {
    dao.deletar(entidade);
    return "Excluído com sucesso!";
}

public E buscarPorId(Class<E> clazz, Long id) {
    return dao.buscarPorId(clazz, id);
}

public List<E> listar(Class<E> clazz) {
    return dao.listar(clazz);
}

public List<E> listarAtivos(Class<E> clazz) {
    return dao.listarAtivos(clazz);
}

public int total(E pesquisa) {
    return this.dao.total(pesquisa);
}

public List<E> listarLazy(E pesquisa, int startingAt, int maxPerPage,
        String sortField, String sortOrder) {
    inicializarCamposPesquisa(pesquisa);
    return this.dao.listarLazy(pesquisa, startingAt, maxPerPage, sortField,
            sortOrder);
}

protected void inicializarCamposPesquisa(E pesquisa) {
    //método que deverá ser implementado pelas classes filhas que quiserem filtrar os resultados no lazyList
}

protected boolean registroJaExiste(Object entidade) {
    Long id = null;
    try {
        id = (Long) entidade.getClass().getMethod("getId").invoke(entidade);
    } catch (IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException
            | SecurityException e) {
        LOGGER.error(
                "Problema ao utilizar Reflection para saber se registro já existe",
                e);
    }
    return id != null;
}

}

persistence.xml:

<?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_2_0.xsd" version="2.0">
<persistence-unit name="pu" transaction-type="JTA">
    <description>Minha conexao</description>
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>java:jboss/jdbc/Postgresql</jta-data-source>

    <properties>
        <!-- Datasource -->
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>

  <property name="hibernate.hbm2ddl.auto" value="update"/>
  <property name="hibernate.show_sql" value="true"/>
  <property name="hibernate.format_sql" value="true"/>
  <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
  <property name="hibernate.transaction.flush_before_completion" value="true"/>

    </properties>
</persistence-unit>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.inbit</groupId>
<artifactId>nomeDOProjeto</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>nomeDOProjeto</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <jetty.version>6.1.4</jetty.version>
</properties>


<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>jsr250-api</artifactId>
            <version>1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>javax.faces-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.spec</groupId>
            <artifactId>jboss-javaee-6.0</artifactId>
            <version>3.0.2.Final</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>



<dependencies>

    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.0-api</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.annotation</groupId>
        <artifactId>jsr250-api</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.spec.javax.ejb</groupId>
        <artifactId>jboss-ejb-api_3.1_spec</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.faces</groupId>
        <artifactId>javax.faces-api</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.spec.javax.servlet</groupId>
        <artifactId>jboss-servlet-api_3.0_spec</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.0.0.GA</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.0.1.Final</version>
    </dependency>

    <!-- JPA Persistence Dependencies -->

    <dependency>
        <groupId>hsqldb</groupId>
        <artifactId>hsqldb</artifactId>
        <version>1.8.0.10</version>
    </dependency>

    <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.1-901-1.jdbc4</version>
    </dependency>

    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>5.0</version>
    </dependency>


    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.6</version>
    </dependency>

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>1.9.5</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.web</groupId>
        <artifactId>el-impl</artifactId>
        <version>2.2</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.5.6</version>
    </dependency>

</dependencies>



<repositories>
    <!-- JBoss Repository used for Java EE 6 pieces -->
    <repository>
        <id>repository.jboss.org</id>
        <name>JBoss Repository</name>
        <url>http://repository.jboss.org/nexus/content/groups/public-jboss/</url>
    </repository>

    <repository>
        <id>prime-repo</id>
        <name>PrimeFaces Maven Repository</name>
        <url>http://repository.primefaces.org</url>
        <layout>default</layout>
    </repository>

</repositories>


<build>
    <finalName>nomeDOProjeto</finalName>
    <plugins>

        <!-- Facilitates downloading source and javadoc in Eclipse -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-eclipse-plugin</artifactId>
            <version>2.8</version>
            <configuration>
                <wtpversion>2.0</wtpversion>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
            </configuration>
        </plugin>

        <!-- Plugin to run and test through maven -->
        <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>maven-jetty-plugin</artifactId>
            <version>6.1.25</version>
            <configuration>
                <scanIntervalSeconds>3</scanIntervalSeconds>
            </configuration>
        </plugin>

        <!-- Ensures we are compiling at 1.7 level -->
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.0</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>

        <!-- Tomcat plugin for embedded tomcat -->
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>tomcat-maven-plugin</artifactId>
            <version>1.1</version>
            <configuration>
                <path>/${project.build.finalName}</path>
            </configuration>
        </plugin>

    </plugins>
</build>

If you need any more class, just say the word.

Thanks in advance for any hint, help and suggestions.

1 answer

3


Use transactions

Note the methods that make any insertion or change in entities with @Transactional.

JPA requires a transaction context to make these changes. This is a recurring problem.

Finding the note

Note that it is not the Spring annotation I am referring to, many frameworks have an annotation with the same name, but the package javax is reserved for Javaee.

The problem in this case is that Hibernate 4.0.1.Final package-dependent jboss-transaction-api_1.1_spec, but this one doesn’t have the annotation @Transactional in Jar. However, it is present from version 1.2 as I checked in the package jboss-transaction-api_1.2_spec.

So the ideal would be to update the Hibernate or API version or to look for an annotation implementation that is compatible with your dependencies.

  • Would not be @Transactional?

  • @Gustavocinque That’s right, said the t. Valew! ;)

  • First I’d like to thank you for the collaboration, but I don’t have that annotation option here, I would just have @Transactionattribute and Transactionmanagement... What would you have to add to bring up this annotation option for me?

  • @Victorcarvalho Not having the option means you can’t import the annotation javax.transaction.Transacional. Take a look at your dependencies, because I have a project here with Hibernate 4.6 and this annotation is imported automatically by Maven through transitive resolution.

  • I even added the two jars below and no showing up... I saw on the Internet that this @Transactional would be from Spring no? <dependency> <groupid>javax.transaction</groupid> <artifactId>jta</artifactId> <version>1.1</version> </dependency> <dependency> <groupid>org.apache.openejb</groupid> <artifactId>openejb-core-Hibernate</artifactId> <version>4.6.0</version> </dependency> .

  • @Victorcarvalho is not from Spring. The package javax is reserved for Javaee. The problem is that Hibernate 4.0.1.Final depends on the jboss-transaction-api_1.1_spec who does not own the @Transactional. However, she is present from the version jboss-transaction-api_1.2_spec.

  • And if instead of using a note @Transactional the annotation was used @Resource above an attribute of the type UserTransaction? So he would do the transaction control "by hand", more or less like this: userTransaction.begin(); or userTransaction.commit(); or userTransaction.rollback();. Or did I talk nonsense? What’s the difference of doing it this way instead of using @Transactional?

  • Oh my dear, without words to thank, adding jboss-transaction-api_1.2_spec in my pom, appeared the annotation and already worked to insert and edit the data! Only the deletion that ended up giving error, but changing to entityManager.remove(entityManager.merge(entity)); worked all beauty. Fight even! Strong hug! EDIT: Testing later, I saw that only updating the version of Hibernate has worked all right too. = D

  • @Electus I think that would also be possible.

  • That’s the correct answer to the question, @Victor?

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.