Как настроить maven hbm2hbmxml и hbm2java для запуска одного за другим в чистой установке mvn - PullRequest
9 голосов
/ 18 января 2010

Мне нужно иметь возможность вызвать mvn clean install и сделать так, чтобы maven вызвал hibernate3: hbm2hbmxml, чтобы сгенерировать файлы сопоставления из базы данных, и после этого вызвать hbm2java, чтобы получить файлы Java, а затем с помощью maven скомпилировать эти вновь созданные файлы Java.Кто-нибудь делал это раньше?

Спасибо

Ответы [ 6 ]

14 голосов
/ 15 сентября 2010

Если вы хотите скомпилировать java-файлы вашей модели (полученные от месторасположения), вам не нужно запускать hbm2hbmxml.

конфигурация плагина:

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>hibernate3-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <components>
                    <component>
                        <name>hbm2java</name>
                        <outputDirectory>src/main/java</outputDirectory>
                        <implementation>jdbcconfiguration</implementation>
                    </component>
                </components>
                <componentProperties>
                    <revengfile>/src/main/resources/reveng/model.reveng.xml</revengfile>
                    <propertyfile>/src/main/resources/META-INF/hibernate.properties</propertyfile>
                    <jdk5>true</jdk5>
                    <ejb3>true</ejb3>
                </componentProperties>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>5.0.8</version>
                </dependency>
                <dependency>
                    <groupId>cglib</groupId>
                    <artifactId>cglib-nodep</artifactId>
                    <version>2.1_3</version>
                </dependency>
            </dependencies>             
        </plugin>
    </plugins>
</build>

hibernate.properties:

hibernate.dialect = org.hibernate.dialect.MySQLInnoDBDialect
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost:3306/YOUR_DB
hibernate.connection.username = yourUsrName
hibernate.connection.password= yourPwd
hibernate.default_schema = YOUR_DB

model.reveng.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering SYSTEM "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
    <table-filter match-name=".*" package="your.package.here" />
</hibernate-reverse-engineering>

Вы запускаете это с:

mvn clean hibernate3:hbm2java compile

если вы хотите, чтобы он был запущен только с:

mvn clean compile

добавьте тег "executeings" в определение вашего плагина

            <executions>
                <execution>
                    <phase>compile</phase>
                    <goals><goal>hbm2java</goal></goals>
                </execution>
            </executions>
5 голосов
/ 09 декабря 2011

Ни один из двух ответов не сработал для меня из коробки. После небольшого исследования я смог сгенерировать POJO из базы данных. Надеюсь, это кто-то быстро отследит.

Просто сгенерируйте Java-файлы - файлы сопоставления не создаются.

Определите соединение с вашей базой данных в src / test / resources / reveng / hibernate.cfg.xml. Использование тестовой ветви, чтобы эти файлы не копировались в распространяемый артефакт.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="pmSessionFactory">
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <!-- Note that we are pointing directly at the catalog so we can use 
             unqualified table names -->
        <property name="hibernate.connection.url">jdbc:oracle:thin:@server.domain.com:1521:catalog</property>
        <property name="hibernate.connection.password">login</property>
        <property name="hibernate.connection.username">****</property>
        <property name="hibernate.default_schema">PM</property>
    </session-factory>
</hibernate-configuration>

Создайте список таблиц, которые вы хотите импортировать. Снова в тестовой ветке: src / test / resources / reveng / model.reveng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC 
  "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" 
  "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >

<hibernate-reverse-engineering>
  <!-- This assumes your database connection is pointing to the proper catalog -->
  <!-- To get all tables in the named schema, use the following 
       <schema-selection match-schema="PM" />
  -->
  <!--  to get only the named tables -->
  <schema-selection match-schema="PM" match-table="PM_PROPERTY"/>
  <schema-selection match-schema="PM" match-table="PM_APPLICATION"/>
  <schema-selection match-schema="PM" match-table="PM_PROPERTY_TYPE"/>
</hibernate-reverse-engineering>

Добавьте плагин hibernate3 maven к вашему помпоненту

<build>
  <plugins>
    ...
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>hibernate3-maven-plugin</artifactId>
      <version>2.2</version>
      <configuration>
        <components>
          <component>
            <name>hbm2java</name>
            <outputDirectory>src/main/java/com/me/examples/pm/data</outputDirectory>
            <implementation>jdbcconfiguration</implementation>
          </component>
        </components>
        <componentProperties>
          <!-- Storing the reveng files in the test branch means we are not 
               deploying connection information-->
          <revengfile>src/test/resources/reveng/model.reveng.xml</revengfile>
          <configurationfile>src/test/resources/reveng/hibernate.cfg.xml</configurationfile>
          <jdk5>true</jdk5>
          <ejb3>true</ejb3>
        </componentProperties>
      </configuration>
      <dependencies>
        <dependency>
          <groupId>com.oracle</groupId>
          <artifactId>classes12</artifactId>
          <version>10.2.0.1.0</version>
        </dependency>
        <dependency>
          <groupId>cglib</groupId>
          <artifactId>cglib-nodep</artifactId>
          <version>2.1_3</version>
        </dependency>
      </dependencies>
    </plugin>
  </plugins>
</build>

Run Maven

mvn hibernate3:hbm2java
1 голос
/ 02 октября 2015

Рабочий пример для hibernate3-maven-plugin версия 3.0 & hbm2java

<profile>
    <id>hbm2java</id>
    <build>
    <plugins>
        <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>hibernate3-maven-plugin</artifactId>
        <version>3.0</version>
        <configuration>
            <hibernatetool>
            <classpath>
                <path location="${project.build.directory}/classes" />
            </classpath>
            <jdbcconfiguration propertyfile="${basedir}/helper/hibernate.properties" revengfile="${basedir}/helper/hibernate-reverse-engineering.xml"
                reversestrategy="de.hibernate.ExampleStrategy" />
            <hbm2java jdk5="true" ejb3="true" destdir="${project.build.sourceDirectory}" />
            </hibernatetool>
        </configuration>
        <executions>
            <execution>
            <goals>
                <goal>hbm2java</goal>
            </goals>
            <!-- must be compile or higher to find ExampleStrategy class in same project -->
            <phase>compile</phase>
            </execution>
        </executions>
        <dependencies>
            <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.3.2.GA</version>
            </dependency>
            <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.1_3</version>
            </dependency>
            <dependency>
            <groupId>com.oracle.jdbc</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>${ojdbc6.version}</version>
            </dependency>
        </dependencies>
        </plugin>
    </plugins>
    </build>
</profile>
1 голос
/ 18 января 2010

Жизненный цикл Maven

mvn clean dependency:copy-dependencies package

Если это должно было быть выполнено, сначала будет выполняться чистая фаза (то есть она будет запускать все предыдущие фазы чистого жизненного цикла, плюс сама чистая фаза), а затем - зависимость: цель копирования-зависимостей, прежде чем наконец выполнить фаза пакета (и все предыдущие фазы сборки жизненного цикла по умолчанию).

Итак, возможно :

mvn clean hibernate3:hbm2hbmxml hibernate3:hbm2java package

Тем не менее, я бы рекомендовал не создавать постоянно классы. Это делает тебя очень негибким.

После вашего комментария это выглядит как "неразумное" поведение из плагина гибернации. Вы можете обойти это, «вручную» скопировав нужные файлы в нужный каталог, используя плагин Maven antrun .

0 голосов
/ 31 июля 2013

Добавьте плагин Hibernate 2 в свой pom:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>hibernate3-maven-plugin</artifactId>
    <version>2.2</version>

            <executions>
                <execution>
                    <id>generate-mapping-files</id>
                    <phase>compile</phase>

                 <goals>
                    <goal>hbm2hbmxml</goal>
                    <goal>hbm2cfgxml</goal>
                    <goal>hbm2java</goal>
                </goals>
...

Тогда в модели Ревенг поставь это.

<!-- Primary Tables -->
 <schema-selection match-schema="TEST_SCHEMA" match-table="TEST_TABLE" />

Затем просто создайте свой проект в Maven, используя clean install, и классы моделей будут автоматически сгенерированы из базы данных.

0 голосов
/ 20 января 2010

у меня работает следующий конфиг. (образец с базой данных Derby и 1 таблицей)
Чистый пакет mvn делает все это.

конфигурация плагина:

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>hibernate3-maven-plugin</artifactId>
<version>2.2</version>
<executions>
    <execution>
        <id>hbm2hbmxml</id>
        <phase>generate-sources</phase>
        <goals>
            <goal>hbm2hbmxml</goal>
        </goals>
        <configuration>
            <components>
                <component>
                    <name>hbm2hbmxml</name>
                    <outputDirectory>src/main/resources</outputDirectory>
                </component>
            </components>
        </configuration>
    </execution>
    <execution>
        <id>hbm2java</id>
        <phase>generate-sources</phase>
        <goals>
            <goal>hbm2java</goal>
        </goals>
        <configuration>
            <components>
                <component>
                    <name>hbm2java</name>
                    <implementation>configuration</implementation>
                </component>
            </components>
            <componentProperties>
                <jdk5>true</jdk5>
                <configurationfile>/src/main/resources/hibernate.cfg.xml
                </configurationfile>
            </componentProperties>
        </configuration>
    </execution>
</executions>
<dependencies>
    <dependency>
        <groupId>org.apache.derby</groupId>
        <artifactId>derbyclient</artifactId>
        <version>10.4.2.0</version>
    </dependency>
</dependencies>

hibernate.cfg.xml:

<hibernate-configuration>
<session-factory>
    <property name="connection.url">jdbc:derby://localhost:1527/demo</property>
    <property name="connection.username">app</property>
    <property name="connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
    <property name="dialect">org.hibernate.dialect.DerbyDialect</property>
    <property name="connection.password">password</property>
    <property name="hibernate.show_sql">true</property>

    <mapping resource="Tag.hbm.xml" />
</session-factory>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...