在休眠4-春季4设置中,可以使用SchemaExport
对象生成DDL:
LocalSessionFactoryBean sfb = (LocalSessionFactoryBean) context.getBean("&sessionFactory");
SchemaExport schema = new SchemaExport(sfb.getConfiguration());
但是休眠5将
SchemaExport(Configuration configuration)
构造函数替换为SchemaExport(MetadataImplementator metadataImplementator)
。MetadataImplementator在以下位置不可用
org.springframework.orm.hibernate5.LocalSessionFactoryBean
或org.springframework.orm.hibernate5.LocalSessionFactoryBuilder
我这样入侵了它:
MetadataSources metadataSources = (MetadataSources) FieldUtils.readField(configuration, "metadataSources", true);
Metadata metadata = metadataSources
.getMetadataBuilder(configuration.getStandardServiceRegistryBuilder().build())
.applyPhysicalNamingStrategy(new MyPhysicialNamingStrategy())
.applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE)
.build();
MetadataImplementor metadataImpl = (MetadataImplementor) metadata;
SchemaExport schema = new SchemaExport(metadataImplementor);
但是最好有一种更好的方法,并且Validator批注(@ NotNull,@ Size)不会用于DDL生成,而且我不知道它是否是Hibernate 5或此设置中的错误。
我正在使用休眠5.0.0.CR4和弹簧4.2.0.RELEASE
最佳答案
您需要实现org.hibernate.integrator.spi.Integrator
,可以在其中将所需数据存储到某个所有者。
您可以在这里找到工作示例https://github.com/valery-barysok/spring4-hibernate5-stackoverflow-34612019
在META-INF/services/org.hibernate.integrator.spi.Integrator
文件中将其注册为服务
public class Integrator implements org.hibernate.integrator.spi.Integrator {
@Override
public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
HibernateInfoHolder.setMetadata(metadata);
HibernateInfoHolder.setSessionFactory(sessionFactory);
HibernateInfoHolder.setServiceRegistry(serviceRegistry);
}
@Override
public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
}
}
用它
new SchemaExport((MetadataImplementor) HibernateInfoHolder.getMetadata()).create(true, true);
new SchemaUpdate(HibernateInfoHolder.getServiceRegistry(), (MetadataImplementor) HibernateInfoHolder.getMetadata()).execute(true, true);
您可以在此处找到其他信息Programmatic SchemaExport / SchemaUpdate with Hibernate 5 and Spring 4
Java Persistence API有
Configuration over Convention
原则,但Validation API仅用于验证目的。验证不是绝对的,您可以在同一字段上放置不同的验证规则。如果你有例如
@Size(max = 50)
@NotNull(groups = DefaultGroup.class)
@Null(groups = SecondGroup.class)
private String shortTitle;
那么它被解释为
@Size(max = 50)
@NotNull(groups = DefaultGroup.class)
@Null(groups = SecondGroup.class)
@Column(length = 255, nullable = true)
private String shortTitle;
在这里查看更多详细信息
Why does Hibernate Tools hbm2ddl generation not take into account Bean Validation annotations?