Execute a Create Table Query through the JPA EntityManager

Laures picture Laures · May 26, 2011 · Viewed 13.4k times · Source

I need to create a new Table in a Database I access through a JPA EntityManager. Do JPA NativeQueries support Queries other than "Select" or "Update"? Or is there another state-of-the-art way to execute a complex SQL query in a JPA Context?

Answer

Augusto picture Augusto · May 27, 2011

The jpa "native queries" can only be used for DML statements (Data Manipulation Language). To issue any DDL, such as a create table, you'll need to get the underlying connection from the EntityManager.

How to extract the connection from the EM will depend on which JPA implementation you're using, but will definitely include invoking EntityManager.getDelegate().

Alternatively (and I think it's a better approach), inject the DataSource or a JDBCTemplate if you're using spring to the object that tries to create the table, and use that class to create the table.