我有应用程序连接到postgres数据库,我需要创建一个临时表来存储数据,然后在作业结束时删除表。
我正在使用JPA,但似乎需要在DB中预先创建表,我不想添加额外的工作来编写sql脚本并且必须在运行作业之前运行它来设置表,所以我创建表在JPA查询中然后做常规的CRUD操作,但它不起作用,是因为JPA无法动态创建表吗?我必须先创建表吗?这是我的代码:
Map<String, String> properties = Maps.newHashMap();
properties.put("javax.persistence.jdbc.url", "jdbc:postgresql://localhost:5432/postgres");
properties.put("javax.persistence.jdbc.user", "postgres");
properties.put("javax.persistence.jdbc.password", "");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("job-postgres", properties);
String queryStr = "CREATE TEMPORARY TABLE tags ("
+ "id SERIAL NOT NULL PRIMARY KEY,"
+ "name varchar(255) NOT NULL,"
+ "type smallint NOT NULL"
+ ")";
Query q = emf.createEntityManager().createQuery(queryStr);
Tag.java:
@Entity
@Table(name="TAGS")
public class Tag implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4762832549003921169L;
@Id
@Column(name="id")
private int _id;
@Basic
@Column(name="name")
private String _name;
@Basic
@Column(name="tagtype")
private int _tagType;
public Tag() {
super();
}
public Tag(String name, int tagType) {
_name = name;
_tagType = tagType;
}
我得到的错误:
2013-Feb-08 14:15:06.574 ERROR o.h.h.PARSER o.h.h.a.ErrorCounter,56 line 1:1: unexpected token: CREATE
Exception in thread "main" java.lang.IllegalArgumentException: node to traverse cannot be null!
at org.hibernate.hql.ast.util.NodeTraverser.traverseDepthFirst(NodeTraverser.java:63)
at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:280)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:182)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:98)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1760)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:268)
答案 0 :(得分:2)
EntityManager.createQuery()
将JPQL查询作为参数。不是SQL查询。
如果要执行SQL查询,请使用EntityManager.createNativeQuery()