Как создать схему базы данных Envers с помощью org.зимовать.инструмент.Энверсшемагенератор?
Я обновил Hibernate до версии 4.1.1.Окончательная версия. Согласно документации
Существует 2 способа создания схемы базы данных:
- Муравьиная задача
org.hibernate.tool.ant.EnversHibernateToolTask. - запустите
org.hibernate.tool.EnversSchemaGeneratorиз Java.
Hibernate-tools не работает с Hibernate-4.1.1.Окончательный. Он имеетблокирующий баг .
Я нашел только примечания к выпуску и тестовый случай.
Итак, как я могу использовать org.hibernate.tool.EnversSchemaGenerator с моей настойчивостью.xml и Мэйвен?
Обновление:
Найден связанныйпоток на форуме Hibernate . Похоже, ответа на мой вопрос пока нет.
4 ответов:
Juplo создалMaven плагин для Hibernate 4 . Плагин поддерживает экспорт схем, включая Envers. Рабочий пример приведен ниже. Проверьтеофициальную документацию по конфигурации плагина , чтобы получить объяснение используемых опций.
Плагин генерирует файл
schema.sqlв каталоге Maven/targetна целиtest. Или вы можете вручную запуститьhibernate4:exportgoal для обновления файла.<project> <build> <plugins> <plugin> <groupId>de.juplo</groupId> <artifactId>hibernate4-maven-plugin</artifactId> <version>1.0.3</version> <executions> <execution> <goals> <goal>export</goal> </goals> </execution> </executions> <configuration> <envers>true</envers> <format>true</format> <delimiter>;</delimiter> <force>true</force> <type>CREATE</type> <target>SCRIPT</target> <hibernateDialect>org.hibernate.dialect.PostgreSQL9Dialect</hibernateDialect> </configuration> </plugin> </plugins> </build> </project>
Вам не нужны инструменты Ant или Hibernate. Довольно легко просто использовать EnversSchemaGenerator напрямую, например:
Configuration config = new Configuration(); //make sure you set the dialect correctly for your database (oracle for example below) config.setProperty("hibernate.dialect","org.hibernate.dialect.Oracle10gDialect"); //add all of your entities config.addAnnotatedClass(MyAnnotatedEntity.class); SchemaExport export = new EnversSchemaGeneHator(config).export(); export.execute(true, false, false, false);Вы также можете дать ему имя файла для записи, но приведенный выше код все равно будет выведен в системный журнал.
Для меня сработало следующее:
public static void main(String[] args) { Ejb3Configuration jpaConfiguration = new Ejb3Configuration().configure("persistenceUnit", null); jpaConfiguration.buildMappings(); Configuration hibernateConfiguration = jpaConfiguration.getHibernateConfiguration(); AuditConfiguration.getFor(hibernateConfiguration); EnversSchemaGenerator esg = new EnversSchemaGenerator(hibernateConfiguration); org.hibernate.tool.hbm2ddl.SchemaExport se = esg.export(); se.setOutputFile("sql/schema.sql"); se.setFormat(true); se.setDelimiter(";"); se.drop(true, false); se.create(true, false); }
У меня та же проблема. Теперь есть версия Hibernate 4 Tools:
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-tools</artifactId> <version>4.0.0-CR1</version> </dependency>Но этот фрагмент муравья не экспортирует таблицы аудита, только "основные" таблицы:
<target name="schema-export"> <taskdef name="hibernatetool" classname="org.hibernate.tool.ant.EnversHibernateToolTask" classpathref="classpath"/> <hibernatetool destdir="sql"> <classpath refid="classpath"/> <jpaconfiguration persistenceunit="persistenceUnit"/> <hbm2ddl export="false" create="true" drop="true" format="true" outputfilename="schema.sql"/> </hibernatetool> </target>То же самое с этим кодом: только "basic", никаких таблиц "_aud":
public static void main(String[] args) { Ejb3Configuration jpaConfiguration = new Ejb3Configuration().configure("persistenceUnit", null); Configuration hibernateConfiguration = jpaConfiguration.getHibernateConfiguration(); AuditConfiguration.getFor(hibernateConfiguration); EnversSchemaGenerator esg = new EnversSchemaGenerator(hibernateConfiguration); org.hibernate.tool.hbm2ddl.SchemaExport se = esg.export(); se.setOutputFile("sql/schema.sql"); se.setFormat(true); se.setDelimiter(";"); se.drop(true, false); se.create(true, false); }Вы все еще заинтересованы? Я дам вам знать, если узнаю, как решить эту проблему. Может быть, у кого-то еще есть для нас какой-нибудь совет?
Comments