【发布时间】:2015-04-19 17:33:14
【问题描述】:
我正在使用以下方式开发应用程序:
- Java 1.7
- JPA(包含在 javaee-api 7.0 中)
- 休眠 4.3.8.Final
- PostgreSQL-JDBC 9.4-1200-jdbc41
- PostgreSQL 9.3.6
我想对一些字符串属性使用 PostgreSQL 文本数据类型。据我所知,在 JPA 中这应该是正确的注释,在 PostgreSQL 中使用文本:
@Entity
public class Product{
...
@Lob
private String description;
....
}
当我这样注释我的实体时,我遇到了如下所示的错误: http://www.shredzone.de/cilla/page/299/string-lobs-on-postgresql-with-hibernate-36.html
简而言之:对于 clob/text-types,hibernate 和 jdbc 似乎并不一致。
所描述的解决方案正在运行:
@Entity
public class Product{
...
@Lob
@Type(type = "org.hibernate.type.TextType")
private String description;
...
}
但这有一个明显的缺点:源代码在编译时需要休眠,这应该是不必要的(这是首先使用 JPA 的原因之一)。
另一种方法是像这样使用列注释:
@Entity
public class Product{
...
@Column(columnDefinition = "text")
private String description;
...
}
效果很好,但是: 现在我坚持使用具有文本类型的数据库(也称为文本;)),如果将来使用另一个数据库,注释很容易被忽略。因此,可能的错误很难找到,因为数据类型是在 String 中定义的,因此在运行之前无法找到。
有没有这么简单的解决方案,我就是没看到?我很确定我不是唯一一个将 JPA 与 Hibernate 和 PostgreSQL 结合使用的人。所以我有点困惑,我找不到更多这样的问题。
为了完成这个问题,persistence.xml 看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="entityManager">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.app.model.Product</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:postgresql://localhost:5432/awesomedb" />
<property name="javax.persistence.jdbc.user" value="usr" />
<property name="javax.persistence.jdbc.password" value="pwd" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.jdbc.use_streams_for_binary" value="false" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
更新:
这个问题或多或少等同于这个问题,选择的答案是这个问题中描述的第二种方法,由于休眠运行时依赖性,我不喜欢这种方法: store strings of arbitrary length in Postgresql
【问题讨论】:
-
既然你在谈论什么是真正的部署问题(自动生成的 DDL),难道你不能在 Postgres 中手动将表创建为 TEXT 而不在类中指定任何内容吗?跨度>
-
是的,我希望能够从休眠中生成数据库。
-
@chrylis 当您这样说时,听起来是错误的 :D 我更喜欢的方式是我首先使用 JPA 方式中的注释(简单地
@Lob)。并让 hibernate/jdbc 在后台发挥作用。我知道,@Lob String应该在 DB2、Oracle 中产生clob,在 H2/HSQLDB 中产生longvarchar,在 MySQL 中产生longtext或text,在 PostgreSQL 中产生text。我的问题是,hibernate 和 postgresql jdbc 会产生错误,应该没有问题。 -
但是 text 和 lob 在语义上不是相同的东西。
-
我正在寻找您想要的相反内容,您的问题就是我的答案。好奇的。我刚刚添加了
columnDefinition = "text"。谢谢。
标签: java hibernate postgresql jpa jdbc