1

我有应用程序连接到 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);

标签.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)
4

1 回答 1

2

EntityManager.createQuery()将 JPQL 查询作为参数。不是 SQL 查询。

如果要执行 SQL 查询,请使用EntityManager.createNativeQuery()

于 2013-02-08T22:36:10.227 回答