10
Sep 2015
by
小川 岳史
Hibernate5 から SchemaExport のコンストラクタの引数が変更され、MetadataImplementor を使うようになった。
以下は、Hibernate5 で Annotation ベースの設定を SQL (DDL) に出力するサンプルです。
public class Hbm2ddl { public static void main(String[] args) throws Exception { final String locationPattern = "classpath:/sample/entity/*"; final BootstrapServiceRegistry registry = new BootstrapServiceRegistryBuilder().build(); final MetadataSources metadataSources = new MetadataSources(registry); final StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder(registry); registryBuilder.applySetting("hibernate.dialect", MySQL5InnoDBDialect.class.getCanonicalName()); final PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); final Resource[] resources = resourcePatternResolver.getResources(locationPattern); final SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); for (Resource resource : resources) { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); AnnotationMetadata metadata = metadataReader.getAnnotationMetadata(); if (metadata.hasAnnotation(Entity.class.getName())) { metadataSources.addAnnotatedClass(Class.forName(metadata.getClassName())); } } final StandardServiceRegistryImpl registryImpl = (StandardServiceRegistryImpl) registryBuilder.build(); final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(registryImpl); new SchemaExport((MetadataImplementor) metadataBuilder.build()) .setHaltOnError(true) .setDelimiter(";") .create(true, false); } }