Execute a Create Table Query through the JPA EntityManager

回眸只為那壹抹淺笑 提交于 2019-12-01 00:31:59

问题


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?


回答1:


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.




回答2:


JPA (at least Hibernate) can let you execute DDL statements directly using createNativeQuery() and executeUpdate() as follows:

EntityManager em = ...;
em.createNativeQuery("CREATE TABLE FOO (FOO_ID NUMBER)").executeUpdate();
em.createNativeQuery("DROP TABLE FOO").executeUpdate();

It's not ideal, but you can do it.



来源:https://stackoverflow.com/questions/6141794/execute-a-create-table-query-through-the-jpa-entitymanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!