项目使用的数据库是postgresql,该数据库支持Json类型。所以在数据库与实体映射时,json类型的字段需要映射为Json类型。
项目的配置:
一直以为这种声明是hibernate本身就支持的类型,像String之类的基础类型一样。但是在将文书的新服务迁移过程中,我自己也需要将某些字段声明为Json类型的,在如上配置,并启动后报错。
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [JsonBType]
本来以为是jar包的问题,对对引用的hibernate相关包做出版本之类修改失败后,再联想到String类型的基础类型可以支持,产生疑问:JsonBtype的类型是不是Hibernate支持。
再去查Hibernate和postgresql相关资料,发现Hibernate是可以注册自己的自定义的类型的。
就上面的JsonBtype类型为例,可以分为3步:
(1)首先需要自定一个Dialect,然后注册到hibernate框架中
(2)实现usertype接口,自定义类型用于实体与数据库映射
- 自定义Dialect注册到Hibernate
public class MyPostgreSQL9Dialect extends PostgreSQL9Dialect {
public MyPostgreSQL9Dialect(){
this.registerColumnType(Types.JAVA_OBJECT,"JsonBType");
}
}
- 自定义 映射规则
public class JsonBType implements UserType {
//实现usertype接口方法定义映射规则
}
- 使用时还需要在实体上增加相关声明
@Entity
@Table(name = "XXXX")
@org.hibernate.annotations.TypeDef(name = "JsonBType", typeClass = JsonBType.class)]
public class XXXX
打完收工。。。