i have application connect to postgres database, i need to create a temporary table to store data, then at the end of job drop the table.
I m using JPA but seems it requires to create the table in DB upfront, i don’t want to add extra work to write the sql script and have to run it to setup table before running the job, so i create table in the JPA query then do regular CRUD operaions, but it doesn’t work, is that because JPA cannot create table on the fly? i have to create the table first? here is my code:
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;
}
error i got:
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()takes a JPQL query as argument. Not a SQL query.If you want to execute a SQL query, use EntityManager.createNativeQuery()