我正在使用hibernate注释,我想导出我的数据库架构。
与使用hbm xml文件的schemaexporttask类似。
答案 0 :(得分:11)
你可以。就这么做吧
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>);
答案 1 :(得分:7)
实际上,原始的Hibernate Core SchemaExportTask
只能处理Hibernate XML映射文件,而不能处理注释。您需要的是Hibernate Tools附带的HibernateToolTask
。
这是一个改编自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>
答案 2 :(得分:6)
如果有人有兴趣如何使用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。诀窍是注入&amp;像这样:“&amp; entityManagerFactory”,取消引用spring生成的代理。
答案 3 :(得分:3)
使用hibernate3-maven-plugin。然后运行'mvn hibernate3:hbm2ddl'