Héctor Valls
Héctor Valls

Reputation: 26094

Generate Java classes from Database Schema without persistence unit

I'm using Spring Boot and I want to generate Java annotated classes from a database schema in IntelliJ.

I go to Persistence -> Generate Persistence Mapping -> By Database Schema but I can't generate classes because I haven't persistence.xml file, so I get the error:

JPA annotation mappings require at least one Persistence Unit

I'm in Spring Boot so... How can I do it?

Upvotes: 1

Views: 3157

Answers (1)

ootero
ootero

Reputation: 3475

If you are using Maven, it could be accomplished using hibernate3-maven-plugin along with .reveng.xml file and Hibernate connection properties.

Here is an example taken from a section of a blog I published a few months ago at: http://tech.asimio.net/2016/08/04/Integration-Testing-using-Spring-Boot-Postgres-and-Docker.html#generating-jpa-entities-from-database-schema

pom.xml

...
<properties>
...
  <postgresql.version>9.4-1206-jdbc42</postgresql.version>
...
</properties>
...
<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>hibernate3-maven-plugin</artifactId>
  <version>2.2</version>
    <configuration>
      <components>
        <component>
          <name>hbm2java</name>
          <implementation>jdbcconfiguration</implementation>
          <outputDirectory>target/generated-sources/hibernate3</outputDirectory>
        </component>
      </components>
      <componentProperties>
        <revengfile>src/main/resources/reveng/db_dvdrental.reveng.xml</revengfile>
        <propertyfile>src/main/resources/reveng/db_dvdrental.hibernate.properties</propertyfile>
        <packagename>com.asimio.dvdrental.model</packagename>
        <jdk5>true</jdk5>
        <ejb3>true</ejb3>
      </componentProperties>
    </configuration>
    <dependencies>
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib-nodep</artifactId>
      <version>2.2.2</version>
    </dependency>
    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <version>${postgresql.version}</version>
    </dependency>              
  </dependencies>
</plugin>
...

db_dvdrental.reveng.xml

...
<hibernate-reverse-engineering>
  <schema-selection match-schema="public" />
</hibernate-reverse-engineering>

db_dvdrental.hibernate.properties

hibernate.connection.driver_class=org.postgresql.Driver
hibernate.connection.url=jdbc:postgresql://localhost:5432/db_dvdrental
hibernate.connection.username=user_dvdrental
hibernate.connection.password=changeit

Generate entities

mvn hibernate3:hbm2java

JPA entities are generated at target/generated-sources/hibernate3 and the resulting package needs to be copied to src/main/java.

Again, http://tech.asimio.net/2016/08/04/Integration-Testing-using-Spring-Boot-Postgres-and-Docker.html provides better instructions and demo source code to accomplish generating JPA entities from existing schema.

Upvotes: 3

Related Questions