Java 如何在使用JPA+;冬眠
因此,我希望始终使用自己的自定义类型来扩展HibernateJava 如何在使用JPA+;冬眠,java,hibernate,jpa,Java,Hibernate,Jpa,因此,我希望始终使用自己的自定义类型来扩展HibernateStringType(还执行修剪和大写)。但是,我在如何注册它方面遇到了一些问题,因此总是使用它而不是默认的StringType,因为我不想在每个字符串上都添加@Type注释 当只使用Hibernate时,我知道我可以使用registerTypeOverride在配置中注册它,或者在hbm.cfg.xml中注册它,但是当将Hibernate与JPA2结合使用时,我如何实现这一点呢?(注意:我知道JPA2.1中有@Convertor wi
StringType
(还执行修剪和大写)。但是,我在如何注册它方面遇到了一些问题,因此总是使用它而不是默认的StringType
,因为我不想在每个字符串上都添加@Type
注释
当只使用Hibernate时,我知道我可以使用registerTypeOverride
在配置中注册它,或者在hbm.cfg.xml
中注册它,但是当将Hibernate与JPA2结合使用时,我如何实现这一点呢?(注意:我知道JPA2.1中有@Convertor with auto=true,但我必须使用的AS还不支持JPA2.1)Hibernate提供了可用于此的接口。例如:
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.
}
}
my-project/
src/main/resources/
META-INF/
services/
org.hibernate.integrator.spi.Integrator
然后需要通过将其公开为通过Java的标准SPI机制进行注册。例如:
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.
}
}
my-project/
src/main/resources/
META-INF/
services/
org.hibernate.integrator.spi.Integrator
其中包含如下内容:
com.example.CustomUserTypesIntegrator
有关此方面的参考,我建议查看如何做到这一点:。特别是,我发现他们的类值得一看。集成器解决方案不适合我(Hibernate 4.2)。在“org.hibernate.internal.sessionfactorympl”中,在调用“积分器”之前创建“typeRegistry”(作为配置的副本)。因此,在“Integrator”中调用“configuration.registerTypeOverride(…)”为时已晚。