gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:56:57 28 4
gpt4 key购买 nike

所以我想始终使用我自己的扩展 Hibernate StringType 的自定义类型(也执行修剪和大写)。但是我在如何注册它方面遇到了一些问题,所以总是使用它而不是默认的 StringType,因为我不想必须放置 @Type 注释在每个字符串上。

当我只使用 Hibernate 时,我知道我可以使用 registerTypeOverride 在配置中注册它,或者在 hbm.cfg.xml 中注册它,但是我如何在使用时实现这一点 hibernate 结合 JPA2? (注意:我知道在 jpa 2.1 中有 @Convertor with auto = true,但是我必须使用的 AS 还不支持 JPA2.1)

最佳答案

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

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.
}
}

然后需要通过将其公开为 Service Provider 来注册通过 Java 的标准 SPI 机制。例如:

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

其中将包含如下内容:

com.example.CustomUserTypesIntegrator

作为引用,我建议查看 Jadira Usertype library这样做:https://github.com/JadiraOrg/jadira/ .特别是,我发现了他们的 AbstractUserTypeHibernateIntegrator类值得一看。

关于java - 使用 JPA + Hibernate 时如何注册自定义 String UserType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19838665/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com