Lau*_*res 8 mysql sql hibernate jpa create-table
我需要在数据库中创建一个新表,我通过JPA EntityManager访问.JPA NativeQueries是否支持"选择"或"更新"以外的查询?或者是否有另一种在JPA上下文中执行复杂SQL查询的最先进方法?
Aug*_*sto 14
jpa"本机查询"只能用于DML语句(数据操作语言).要发出任何DDL,例如create table,您需要从EntityManager获取底层连接.
如何从EM中提取连接将取决于您正在使用的JPA实现,但肯定包括调用EntityManager.getDelegate().
或者(我认为这是一种更好的方法),如果您对尝试创建表的对象使用spring,并使用该类创建表,则注入DataSource或JDBCTemplate.
小智 5
JPA(至少是 Hibernate)可以让你直接使用 createNativeQuery() 和 executeUpdate() 执行 DDL 语句,如下所示:
EntityManager em = ...;
em.createNativeQuery("CREATE TABLE FOO (FOO_ID NUMBER)").executeUpdate();
em.createNativeQuery("DROP TABLE FOO").executeUpdate();
Run Code Online (Sandbox Code Playgroud)
这并不理想,但你可以做到。