robert
robert

Reputation: 3

JPA - Performing an Update

I have the following code:

package testingjpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class Main
{

    public static void main(String[] args)
    {
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("TestingJPAPU");

        EntityManager em = emFactory.createEntityManager();

        Query query = em.createQuery("UPDATE Passengers p SET p.name = 'Robert' WHERE p.id = 2");

        query.executeUpdate();
        em.close();
    }
}

The problem with this code is that it is throwing a TransactionRequiredException. The entity class works fine since I have tried using other code and it worked perfectly. How can I solve this problem please?

Upvotes: 0

Views: 75

Answers (2)

Kurt Du Bois
Kurt Du Bois

Reputation: 7655

You should start and commit/rollback the transaction yourself, since container managed transactions are unusable in your situation.

First you should ask the UserTransaction from the EntityManager. After the query, you should commit or rollback your transaction.

You should also do some decent connection handling: close the entitymanager in a finally-block to circumvent having resource leakage when an exception is thrown from your code.

Upvotes: 3

TheWhiteRabbit
TheWhiteRabbit

Reputation: 15758

@Resource private UserTransaction mytx;
public static void main(String[] args)
    {
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("TestingJPAPU");

        EntityManager em = emFactory.createEntityManager();

        mytx.begin();
        Query query = em.createQuery("UPDATE Passengers p SET p.name = 'Robert' WHERE p.id = 2");

        query.executeUpdate();
        mytx.commit()
        em.close();
    }

Upvotes: 1

Related Questions