编辑: 解决了 。我发现了让我感到困惑的事情。我使用 pgadmin 创建表和其他数据库内部,现在检查:如果名称中的至少一个字母(表名、列名、pk 名等)是大写的,那么 pgadmin 在 SQL 创建脚本中使用它因为它是使用双引号,所以 PostgreSQL 解释它所写的名称。如果运行以下脚本:
CREATE TABLE SAMPLE
(
ID integer NOT NULL,
TITLE character varying(100) NOT NULL,
CONSTRAINT SAMPLE_ID_PK PRIMARY KEY (ID)
)
WITH (
OIDS=FALSE
);
ALTER TABLE SAMPLE
OWNER TO postgres;_
它以小写形式创建所有内容,并且原始 Sample.java 版本工作正常。
这里有什么问题?这个问题是 PostgreSQL 9.1 或一般 PostgreSQL 特有的,还是缺少某些休眠配置?
持久性.xml:
<persistence-unit name="com.sample.persistence.jpa" transaction-type="RESOURCE_LOCAL">
<class>com.sample.persistence.Sample</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.connection.url" value="jdbc:postgresql:sample"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="hibernate.connection.username" value="postgres"/>
<property name="hibernate.connection.password" value="postgres"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
示例.java:
@Entity
@Table(name = "SAMPLE")
public class Sample {
@Id
@Column(name = "ID")
private long id;
@Column(name = "TITLE")
private String title;
public String getTitle() {
return title;
}
}
PersistenceMain.java:
public class PersistenceMain {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.sample.persistence.jpa");
EntityManager em = emf.createEntityManager();
Sample sample = em.find(Sample.class, 1l);
System.out.println("Sample Title: " + sample.getTitle());
em.close();
emf.close();
}
}
例外:
...
Hibernate:
select
sample0_.ID as ID0_0_,
sample0_.TITLE as TITLE0_0_
from
SAMPLE sample0_
where
sample0_.ID=?
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not load an entity: [com.sample.persistence.Sample#1]
...
Caused by: org.postgresql.util.PSQLException: ERROR: relation "sample" does not exist
...
显然,上面的这条 SQL 语句:
select
sample0_.ID as ID0_0_,
sample0_.TITLE as TITLE0_0_
from
SAMPLE sample0_
where
sample0_.ID=?
没有从 PostgreSQL 本身(来自 pgadmin)成功执行。
但是,如果我将 Sample.java 更改为:
@Entity
@Table(name = "\"SAMPLE\"")
public class Sample {
@Id
@Column(name = "\"ID\"")
private long id;
@Column(name = "\"TITLE\"")
private String title;
public String getTitle() {
return title;
}
}
这很奇怪,它有效。
Hibernate:
select
sample0_."ID" as ID1_0_0_,
sample0_."TITLE" as TITLE2_0_0_
from
"SAMPLE" sample0_
where
sample0_."ID"=?
Sample Title: Sample
hibernate.dialect 在这里没用,还是不能在 PostgreSQL 9.1 上正常工作?另外,如果它们与字段相同,我不想输入列名,但是在大写中,这也可能吗?
谢谢你。