我正在使用休眠注释,我想导出我的数据库模式。
类似于带有 hbm xml 文件的 schemaexporttask。
你可以。去做就对了
AnnotationConfiguration configuration = new AnnotationConfiguration();
configuration
.addAnnotatedClass(<TYPE_YOUR_CLASS>.class)
.setProperty(Environment.USER, <TYPE_YOUR_USER>)
.setProperty(Environment.PASS, <TYPE_YOUR_PASSWORD>)
.setProperty(Environment.URL, <TYPE_YOUR_URL>)
.setProperty(Environment.DIALECT, <TYPE_YOUR_DIALECT>)
.setProperty(Environment.DRIVER, <TYPE_YOUR_DRIVER>);
SchemaExport schema = new SchemaExport(configuration);
schema.setOutputFile("schema.sql");
schema.create(<DO_YOU_WANT_TO_PRINT_TO_THE_CONSOLE>, <DO_YOU_WANT_TO_EXPORT_THE_SCRIPT_TO_THE_DATABASE>);
事实上,原来的 Hibernate CoreSchemaExportTask
只能处理 Hibernate XML 映射文件,不能处理注解。您需要的是Hibernate ToolsHibernateToolTask
附带的。
这是改编自 Java Persistence With Hibernate 的用法示例:
<taskdef name="hibernatetool"
classname="org.hibernate.tool.ant.HibernateToolTask"
classpathref="project.classpath"/>
<target name="schemaexport" depends="compile, copymetafiles"
description="Exports a generated schema to DB and file">
<hibernatetool destdir="${basedir}">
<classpath path="${build.dir}"/>
<configuration
configurationfile="${build.dir}/hibernate.cfg.xml"/>
<hbm2ddl
drop="true"
create="true"
export="true"
outputfilename="helloworld-ddl.sql"
delimiter=";"
format="true"/>
</hibernatetool>
</target>
如果有人对如何从单元测试中使用 JPA+Spring 执行此操作感兴趣(您可以像轻而易举地从 Eclipse 内部生成运行单元测试的 sql):
ExportDatabaseSchema.java:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TransactionConfiguration(defaultRollback=true)
public class ExportDatabaseSchema {
@Resource(name="&entityManagerFactory")
private LocalContainerEntityManagerFactoryBean entityManagerFactory;
@Test
public void exportDatabaseSchema(){
PersistenceUnitInfo persistenceUnitInfo = entityManagerFactory.getPersistenceUnitInfo();
Map jpaPropertyMap = entityManagerFactory.getJpaPropertyMap();
Configuration configuration = new Ejb3Configuration().configure( persistenceUnitInfo, jpaPropertyMap ).getHibernateConfiguration();
SchemaExport schema = new SchemaExport(configuration);
schema.setOutputFile("resources/sql/schema.sql");
schema.create(false, false);
}
}
您需要一个 ExportDatabaseSchema-context.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<import resource="classpath:applicationContext-jpa.xml" />
</beans>
applicationContext-jpa.xml 包含注解配置的 entityManagerFactory bean。诀窍是用 & 像这样注入它:“&entityManagerFactory”,以取消引用 spring 生成的代理。
使用 hibernate3-maven-plugin。然后运行'mvn hibernate3:hbm2ddl'