1

I'm using entity manager to create a table with native query,and insert rows to another table with em.persist(). when the native query which is create table failed,I rolled back,but the em.persist() is always successful.Does anyone know the answer??

I wrote the wrong sql in purpose to make it into catch.

try {
    tx.begin();
    table1 t1 = new table1();
    t1.setC1(c1);
    t1.setC2(c2);
    EntityManager em = emf.createEntityManager();
    em.persist(t1);
    Query query1= em.createNativeQuery("drop table if exists table2").executeUpdate();
    Query query2= em.createNativeQuery("xxxxxxxxxxxxxxxx").executeUpdate();
    tx.commit();
    rt = true;
} catch (Exception e) {
    try {
        tx.rollback();
    } catch (Exception e1) {
        PUB.log(e, PUB.getLineInfo());
    }
}

here is the persistence.xml and i'm using Mysql5.6:

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class MainSessionBean implements MainSessionBeanRemote {
    @PersistenceUnit(unitName = "CC2016JPA2")
    static EntityManagerFactory emf;
    @Resource
    UserTransaction tx;
Jianspf
  • 11
  • 4

1 Answers1

4

I'm not sure if I understand your question, but I think you want to rollback a CREATE TABLE statement. You can't do that, as CREATE TABLE causes an implicit COMMIT and end the transaction.

See the documentation for implicit-commit:

The statements listed in this section (and any synonyms for them) implicitly end any transaction active in the current session, as if you had done a COMMIT before executing the statement.

...

The CREATE TABLE statement in InnoDB is processed as a single transaction. This means that a ROLLBACK from the user does not undo CREATE TABLE statements the user made during that transaction.

baao
  • 71,625
  • 17
  • 143
  • 203
  • Thank you Baao, actually I want to rollback the em.persist(t1),but it's not what I experted. em.persist() still works. – Jianspf Nov 18 '16 at 02:36