是否有任何可用于连接数据库的hibernate实用程序。列出所有表,并为“创建表+数据”生成sql脚本并另存为* .sql?
答案 0 :(得分:7)
将数据从数据库导出为sql
使用liquibase开源项目
LiquiBase是一个开源(LGPL),独立于数据库的库,用于跟踪,管理和应用数据库更改。它建立在一个简单的前提上:所有数据库更改(结构和数据)都以基于XML的描述方式存储,并检入源代码控制。
为给定的JPA实体生成创建和删除脚本
我们使用此代码生成drop和create语句: 只需使用所有实体类构造此类并调用create / dropTableScript。
如果需要,您可以使用persitence.xml和persitance单元名称。随便说点 我也发布了这段代码。
import java.util.Collection;
import java.util.Properties;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.dialect.Dialect;
import org.hibernate.ejb.Ejb3Configuration;
/**
* SQL Creator for Tables according to JPA/Hibernate annotations.
*
* Use:
*
* {@link #createTablesScript()} To create the table creationg script
*
* {@link #dropTablesScript()} to create the table destruction script
*
*/
public class SqlTableCreator {
private final AnnotationConfiguration hibernateConfiguration;
private final Properties dialectProps;
public SqlTableCreator(final Collection<Class<?>> entities) {
final Ejb3Configuration ejb3Configuration = new Ejb3Configuration();
for (final Class<?> entity : entities) {
ejb3Configuration.addAnnotatedClass(entity);
}
dialectProps = new Properties();
dialectProps.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
hibernateConfiguration = ejb3Configuration.getHibernateConfiguration();
}
/**
* Create the SQL script to create all tables.
*
* @return A {@link String} representing the SQL script.
*/
public String createTablesScript() {
final StringBuilder script = new StringBuilder();
final String[] creationScript = hibernateConfiguration.generateSchemaCreationScript(Dialect
.getDialect(dialectProps));
for (final String string : creationScript) {
script.append(string).append(";\n");
}
script.append("\ngo\n\n");
return script.toString();
}
/**
* Create the SQL script to drop all tables.
*
* @return A {@link String} representing the SQL script.
*/
public String dropTablesScript() {
final StringBuilder script = new StringBuilder();
final String[] creationScript = hibernateConfiguration.generateDropSchemaScript(Dialect
.getDialect(dialectProps));
for (final String string : creationScript) {
script.append(string).append(";\n");
}
script.append("\ngo\n\n");
return script.toString();
}
}