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

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.

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;
		}

Thank you @dreab8,

Worked perfectly.

Thank you again.

I tried this approach with our existing entity manger injected by @Autowire, but get this error:

java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead. I dont have an entityManagerFactory.

Unfortunately, I have no idea how to use either.

This is the Hibernate forum, so please ask your questions about Spring transactions in a Spring forum instead.