gpt4 book ai didi

postgresql - jpa创建表

转载 作者:行者123 更新时间:2023-11-29 13:05:19 26 4
gpt4 key购买 nike

我有应用程序连接到 postgres 数据库,我需要创建一个临时表来存储数据,然后在作业结束时删除该表。

我正在使用 JPA,但似乎它需要预先在数据库中创建表,我不想添加额外的工作来编写 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)

最佳答案

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

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

关于postgresql - jpa创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14782340/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com