
ddl语句
不久前,我必须使用内存数据库。 该活动与集成测试有关。 如您所知,通常将内存数据库用于集成测试。 造成这种情况的原因有很多:可移植性,良好的环境基础结构,高性能,原始数据库的一致性。
问题在于如何将生产DDL模式整合到测试内存数据库中。 第一个是MySQL ,第二个是HSQLDB 。 MySQL的语法不同于HSQL语法。 因此,如果不进行适当的转换,就不可能将MySQL表模式导入HSQLDB。
坦白说,我已经花了很多时间在寻找一些解决方案,这将有助于我在HSQL中导入MySQL DDL模式。 结果不是我想要的那么好。 所有解决方案都是商业性的,或者不是自动的,例如,替换HSQL上的所有MySQL特定代码。
幸运的是,我的项目使用Hibernate作为JPA实现。 所有实体都装饰有适当的Hibernate注释。 正如您将进一步看到的那样,这对于MySQL模式的转换将非常有帮助。 Hibernate提供了基于DDL生成实体的机制,反之亦然。 因此,任何使用Hibernate注释修饰的实体都可以使用Hibernate支持的DB语言来表示为表模式。
这是一个解决我的问题的类:
public class SchemaTranslator {
private Configuration config = null;
public SchemaTranslator() {
config = new Configuration();
}
public SchemaTranslator setDialect(String dialect) {
config.setProperty(AvailableSettings.DIALECT, dialect);
return this;
}
/**
* Method determines classes which will be used for DDL generation.
* @param annotatedClasses - entities annotated with Hibernate annotations.
*/
public SchemaTranslator addAnnotatedClasses(Class[] annotatedClasses) {
for (Class clazz : annotatedClasses)
config.addAnnotatedClass(clazz);
return this;
}
/**
* Method performs translation of entities in table schemas.
* It generates 'CREATE' and 'DELETE' scripts for the Hibernate entities.
* Current implementation involves usage of {@link #write(FileOutputStream, String[], Formatter)} method.
* @param outputStream - stream will be used for *.sql file creation.
* @throws IOException
*/
public SchemaTranslator translate(FileOutputStream outputStream) throws IOException {
Dialect requiredDialect = Dialect.getDialect(config.getProperties());
String[] query = null;
query = config.generateDropSchemaScript(requiredDialect);
write(outputStream, query, FormatStyle.DDL.getFormatter());
query = config.generateSchemaCreationScript(requiredDialect);
write(outputStream, query, FormatStyle.DDL.getFormatter());
return this;
}
/**
* Method writes line by line DDL scripts in the output stream.
* Also each line logs in the console.
* @throws IOException
*/
private void write(FileOutputStream outputStream, String[] lines, Formatter formatter)
throws IOException {
String tempStr = null;
for (String line : lines) {
tempStr = formatter.format(line)+";";
System.out.println(tempStr);
outputStream.write(tempStr.getBytes());
}
}
public static void main(String[] args) throws IOException {
SchemaTranslator translator = new SchemaTranslator();
Class[] entityClasses = {Smartphone.class};
translator.setDialect("org.hibernate.dialect.HSQLDialect")
.addAnnotatedClasses(entityClasses)
.translate(new FileOutputStream(new File("db-schema.sql")));
}
}
上面的代码非常冗长,但我对此进行了评论。 因此,我希望它或多或少容易理解。 整个应用程序的代码可以在GitHub上找到。 SchemaTranslator类在项目结构中具有以下位置:
- / src / test / java / com / mobapp / test / util /
借助此类,您可以将您的实体采用到Hibernate支持的任何必需数据库中。
祝好运!
翻译自: https://www.javacodegeeks.com/2014/01/hibernate-ddl-schema-generation.html
ddl语句