繁体   English   中英

使用JPA + Hibernate时如何注册自定义String UserType

[英]How to register custom String UserType when using JPA + Hibernate

因此,我想始终使用自己的自定义类型来扩展Hibernate StringType (还执行修剪和大写)。 但是我在如何注册它上有一些问题,因此总是使用它而不是默认的StringType ,因为我不想在每个String上都使用@Type注释。

当我只使用Hibernate时,我知道我可以使用registerTypeOverridehbm.cfg.xml在Configuration中进行registerTypeOverride ,但是当结合使用Hibernate和JPA2时如何实现呢? (注意:我知道在jpa 2.1中有@ Convertor,auto = true,但是我必须使用的AS还不支持JPA2.1)

Hibernate提供了可用于此目的的Integrator接口。 例如:

public class CustomUserTypesIntegrator implements Integrator {
    public void integrate(Configuration configuration,
            SessionFactoryImplementor sessionFactory,
            SessionFactoryServiceRegistry serviceRegistry) {
        // Register the custom user type mapping(s) with Hibernate.
        CustomUserType customUserType = new CustomUserType();
        configuration.registerTypeOverride(customUserType,
                new String[] { customUserType.returnedClass().getName() });
    }

    public void integrate(MetadataImplementor metadata,
            SessionFactoryImplementor sessionFactory,
            SessionFactoryServiceRegistry serviceRegistry) {
        // Nothing to do here.
    }

    public void disintegrate(SessionFactoryImplementor sessionFactory,
            SessionFactoryServiceRegistry serviceRegistry) {
        // Nothing to do here.
    }
}

然后需要通过Java的标准SPI机制将其公开为服务提供者来进行注册。 例如:

my-project/
  src/main/resources/
    META-INF/
      services/
        org.hibernate.integrator.spi.Integrator

其中包含以下内容:

com.example.CustomUserTypesIntegrator

有关此的参考,我建议查看Jadira Usertype库是如何做到的: https : //github.com/JadiraOrg/jadira/ 特别是,我发现他们的AbstractUserTypeHibernateIntegrator类值得一看。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM