You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hibernate5.3实现CompositeUserType时如何获取自定义UserType对应的Type对象

Hibernate 5.3版本CompositeUserType自定义属性类型实现方案

Hibernate 5.x版本移除了旧版的Hibernate.custom()方法后,可通过org.hibernate.type.CustomType适配器类包装自定义UserType实现,来完成getPropertyTypes()方法的逻辑。

基础实现方式

直接实例化CustomType,传入你实现的UserType对象即可:

import org.hibernate.type.CustomType;
import org.hibernate.type.Type;

// 你的CompositeUserType实现类中的getPropertyTypes方法
public Type[] getPropertyTypes() {
    return new Type[] {
        new CustomType(new MyUserType1()),
        new CustomType(new MyUserType2())
    };
}

性能优化写法

如果你的自定义UserType是无状态实现,建议提前创建为静态常量,避免重复实例化:

import org.hibernate.type.CustomType;
import org.hibernate.type.Type;

public class MyCompositeUserType implements CompositeUserType {
    // 提前初始化自定义类型常量
    private static final Type MY_USER_TYPE_1 = new CustomType(new MyUserType1());
    private static final Type MY_USER_TYPE_2 = new CustomType(new MyUserType2());

    @Override
    public Type[] getPropertyTypes() {
        return new Type[] {MY_USER_TYPE_1, MY_USER_TYPE_2};
    }

    // 其他CompositeUserType接口方法实现...
}

可复用注册方式

如果需要在多个位置使用同一个自定义类型,可以提前将其注册到Hibernate的TypeConfiguration中,后续直接调用获取即可:

// 项目初始化阶段,从SessionFactory实例中获取TypeConfiguration并注册类型
TypeConfiguration typeConfig = sessionFactory.getTypeConfiguration();
typeConfig.getTypeResolver().registerTypeOverride(
    new CustomType(new MyUserType1()),
    new String[]{"customType1"}
);

// 在getPropertyTypes方法中直接获取注册好的类型
public Type[] getPropertyTypes() {
    return new Type[] {
        typeConfig.getTypeResolver().basic("customType1")
    };
}

内容的提问来源于stack exchange,提问作者John S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:36:03