使用Maven实现JPA逆向工程

来源:互联网 发布:淘宝店图片怎么制作的 编辑:程序博客网 时间:2024/06/16 02:45

本文JPA逆向工程(reverse engineering)并不依赖于IDE相关插件的图形化操作,而是直接构建使用hibernate-tools的Maven项目去实现。

hibernate-tools项目主页 https://github.com/hibernate/hibernate-tools

下面是一个简单的例子,假设数据库使用MySQL。
过程如下:
0、新建一个Maven项目
1、在src/main/resources目录下新建一个hibernate.properties文件,加入下面内容:

hibernate.dialect org.hibernate.dialect.MySQL57Dialecthibernate.connection.driver_class com.mysql.jdbc.Driverhibernate.connection.username roothibernate.connection.password roothibernate.connection.url jdbc:mysql:///sakila?useSSL=truehibernate.default_catalog sakila

2、在pom.xml文件内添加如下代码:

<!--build标签--><build>    <plugins>        <plugin>            <artifactId>maven-antrun-plugin</artifactId>            <version>1.8</version>            <executions>                <execution>                    <id>hbm2java</id>                    <configuration>                        <target>                            <taskdef name="hibernatetool"                                     classname="org.hibernate.tool.ant.HibernateToolTask"/>                            <hibernatetool>                                <jdbcconfiguration packagename="entity"                                                   propertyfile="src/main/resources/hibernate.properties"/>                                <hbm2java destdir="src/main/java" jdk5="true" ejb3="true"/>                            </hibernatetool>                        </target>                    </configuration>                    <goals>                        <goal>run</goal>                    </goals>                </execution>            </executions>            <dependencies>                <dependency>                    <groupId>org.hibernate</groupId>                    <artifactId>hibernate-tools</artifactId>                    <version>RELEASE</version>                    <exclusions>                        <exclusion>                            <groupId>org.eclipse.jdt</groupId>                            <artifactId>org.eclipse.jdt.core</artifactId>                        </exclusion>                    </exclusions>                </dependency>                <dependency>                    <groupId>mysql</groupId>                    <artifactId>mysql-connector-java</artifactId>                    <version>[5.1.45,6)</version>                </dependency>            </dependencies>        </plugin>    </plugins></build>

3、使用如下命令运行Maven项目:

mvn antrun:run@hbm2java

4、完成
在src/main/java目录下可看到生成的实体类。

补充:
pom.xml中jdbcconfiguration标签可以配置更多的属性,
例如 revengfile=”src/main/resources/hibernate.reveng.xml”,
可以参考 JDBCConfigurationTask.java ,
hibernate.reveng.xml的配置可以参考文档。