如果对 BasicTypeRegistry 中隐式选择 Hibernate type 的结果不满意,也可以通过 @org.hibernate.annotations.Type 显式指定 Hibernate type
org.hibernate.annotations.Type 的 type 属性可以取值:
- org.hibernate.type.Type 实现类的全名
- BasicTypeRegistry 的 key
- type definition(@org.hibernate.annotations.TypeDef) 的 name
package org.example.demo.hibernate;
import javax.persistence.Entity;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Id;
import javax.persistence.Persistence;
public class Test {
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
factory.close();
}
@Entity(name = "Product")
public static class Product {
@Id
Integer id;
@org.hibernate.annotations.Type(type = "integer")
String sku;
}
}
生成的 SQL
drop table if exists Product cascade
create table Product (id int4 not null, sku int4, primary key (id))
原文档中的例子
package org.example.demo.hibernate;
import javax.persistence.Entity;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Id;
import javax.persistence.Persistence;
public class Test {
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
factory.close();
}
@Entity(name = "Product")
public static class Product {
@Id
Integer id;
String sku;
@org.hibernate.annotations.Type(type = "nstring")
String name;
@org.hibernate.annotations.Type(type = "materialized_nclob")
String description;
}
}
生成 SQL
drop table if exists Product cascade
create table Product (id int4 not null, description nclob, name nvarchar(255), sku varchar(255), primary key (id))
但是执行 DDL 时出错
- org.postgresql.util.PSQLException: 错误: 类型 "nclob" 不存在
- org.postgresql.util.PSQLException: 错误: 类型 "nvarchar" 不存在