Correct JPA Annotation for PostgreSQL's text type without Hibernate Annotations

前端 未结 4 2049
抹茶落季
抹茶落季 2020-12-15 16:28

I\'m developing an application using:

  • Java 1.7
  • JPA (included in javaee-api 7.0)
  • Hibernate 4.3.8.Final
  • PostgreSQL-JDBC 9.4-1200-jdbc4
相关标签:
4条回答
  • 2020-12-15 17:09

    I would go with simple private String description;. The column type is only a problem if you are generating the database from your code, because it will be generated as varchar instead of text.

    It is great to code in database agnostic way, and without any JPA vendor specific things, but there are cases where this just isn't possible. If the reality is that you will have to support multiple database types with all their specifics, then you have to account for those specifics somewhere. One option is to use columnDefinition for defining column type. Another is to leave the code as it is, and just change the column type in the database. I prefer the second one.

    0 讨论(0)
  • 2020-12-15 17:13

    I just had to add this annotation:

    @Column(columnDefinition="TEXT")
    

    It did not work on its own. I had to recreate the table in the database.

    DROP TABLE yourtable or just alter column type to text with ALTER TABLE statement

    0 讨论(0)
  • 2020-12-15 17:22

    Since the text type is not a part of the SQL standard there is no official JPA way I guess.

    However, the text type is quite similar to varchar, but without the length limit. You can hint the JPA implementation with the length property of @Column:

    @Column(length=10485760)
    private String description;
    

    Update: 10 MiB seems to be the maximum length for varchar in postgresql. The text is almost unlimited, according the documentation:

    In any case, the longest possible character string that can be stored is about 1 GB.

    0 讨论(0)
  • 2020-12-15 17:33

    If you want to use plain JPA you could just remap the used CLOB type on the Dialect like this:

    public class PGSQLMapDialect extends PostgreSQL9Dialect {
    
    
      @Override
      public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
        if (Types.CLOB == sqlTypeDescriptor.getSqlType()) {
          return LongVarcharTypeDescriptor.INSTANCE;
        }
        return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
      }
    
    
    }
    

    So it won't use the CLOB mapping from the JDBC driver which uses a OID for the column and stores/loads the text via large object handling. This would just result in setString and getString calls on the createt text column on the Postgres JDBC Driver via the VarcharTypeDescriptor class.

    0 讨论(0)
提交回复
热议问题