我在Oracle上执行hibernate查询有问题:
我的persistence . xml:
<description>ProfileEntityManager</description>
<class>com.entity.User</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect"/>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@XXX:9999/db"/>
<property name="javax.persistence.jdbc.user" value="user"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<property name = "hibernate.show_sql" value = "true" />
</properties>
我的实体类com.entity.User:
package com.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name ="USER", schema = "SCHEMA")
public class User{
@Id
@Column(name = "USER_ID")
private String userId;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
my Java class
//System.out.println(uid);
List<User> lp = null;
try {
lp = em.createNativeQuery("SELECT iu FROM User iu WHERE iu.userId = ?", User.class)
.setParameter(1, uid).getResultList();
} catch (Exception e) {
System.out.println(e.getMessage());
writeLog(fw, e.getMessage());
}
但是当我执行我的代码时,我得到:
Hibernate: SELECT iu FROM User iu WHERE iu.userId = ?
gen 29, 2021 6:36:59 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 942, SQLState: 42000
gen 29, 2021 6:36:59 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-00942: tabella o vista inesistente
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
你能帮我找出错误吗?
注意:如果使用一个PreparedStatement与相同的连接和查询我没有任何问题,所以它不是权限的问题
您尝试使用HQL
查询与EntityManager.createNativeQuery
方法。这是一个错误。
试着用这种方式纠正你的查询:
em.createNativeQuery("SELECT * FROM SCHEMA.USER WHERE USER_ID = :usrid", User.class)
.setParameter("usrid", uid)
.getResultList();
如果你使用SCHEMA
为你所有的实体,你可以把它放在hibernate配置:
<property name="hibernate.default_schema" value="SCHEMA"/>
然后按以下方式更正实体定义:
@Entity
@Table(name ="USER")
public class User {
// ...
}
,然后更正你的查询:
em.createNativeQuery("SELECT * FROM {h-schema}USER WHERE USER_ID = :usrid", User.class)
.setParameter("usrid", uid)
.getResultList();
注:顺便说一下,我建议您更正hibernate方言定义。你应该尽量使用特定的方言。例如,如果您使用Oracle 10g,则应该使用org.hibernate.dialect.Oracle10gDialect
。您仍然可以使用org.hibernate.dialect.Oracle9iDialect
,但Oracle10gDialect
中定义的一些新功能将不可用。
似乎您需要将这一行添加到配置文件
<property name="hbm2ddl.auto">create</prop>
或
<property name="hbm2ddl.auto">update</prop>