CREATE TABLE in JPA and INSERT INTO that table in JPA without Entity


#1

Hello,

I’m using H2 in memory database using JPA. I tried creating table using EntityManager in JPA using

EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.createNativeQuery("CREATE TABLE FOO (FOO_ID NUMBER)").executeUpdate();

But I’m getting the below Exception.

javax.persistence.TransactionRequiredException: Executing an update/delete query

How can I create table and insert data into without Entity.

Thank you.


#2

Hi @padmahasa,
the statement requires to be executed inside a transaction,

EntityTransaction txn = null;
		try {
			EntityManager entityManager = entityManagerFactory().createEntityManager();
			txn = entityManager.getTransaction();
			txn.begin();
			entityManager.createNativeQuery( "CREATE TABLE FOO (FOO_ID NUMBER)" ).executeUpdate();

			txn.commit();
		}
		catch ( Throwable e ) {
			if ( txn != null && txn.isActive() ) {
				txn.rollback();
			}
			throw e;
		}

#3

Thank you @dreab8,

Worked perfectly.

Thank you again.