DB Importer

HiberObjects

Download

Order

Forum

It is currently Thu Jun 20, 2013 8:22 am

All times are UTC + 1 hour [ DST ]




Post new topic Reply to topic  [ 1 post ] 
Author Message
 Post subject: How to use DB Importer with Maven
PostPosted: Tue Dec 14, 2010 12:16 am 
Offline

Joined: Tue Apr 10, 2007 4:42 pm
Posts: 619
Location: Uppsala, Sweden
This example will show how import a database with DB Importer and use Maven to install all the libraries needed for JPA.

You will need:
  • Maven
  • Eclipse
  • The DB Importer Eclipse plug-in. It is available from the update site http://objectgeneration.com/update
  • An existing database to import. I use a PostgreSQL database called "hrm" in this example.

The source code is available here: https://bitbucket.org/larsho/dbimporter/src/6da02af3395a/examples/maven/
You can download it with Mercurial or view it in a browser.

Step 1: Create a new project
From the command line enter the following commands:
Code:
mvn archetype:create -DgroupId=com.objectgen.example -DartifactId=maven
cd maven
mvn eclipse:eclipse
Then start Eclipse and import the new project called "maven" into Eclipse with File > Import > General > Existing projects into workspace

Modify the pom.xml to set source leven to 1.5:
Code:
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.5</source>
          <target>1.5</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

Add dependencies to Hibernate, HSQLDB and PostgreSQL to pom.xml:
Code:
  <repositories>
    <repository>
        <id>JBoss</id>
        <name>JBoss Repsitory</name>
        <layout>default</layout>
        <url>http://repository.jboss.org/maven2</url>
    </repository>
  </repositories>
  <dependencies>
     <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.15</version>
    </dependency>
    <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-core</artifactId>
       <version>3.3.2.GA</version>
    </dependency>
    <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-annotations</artifactId>
       <version>3.4.0.GA</version>
    </dependency>
    <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-commons-annotations</artifactId>
       <version>3.3.0.ga</version>
    </dependency>
    <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-entitymanager</artifactId>
       <version>3.4.0.GA</version>
    </dependency>
    <dependency>
      <groupId>postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <version>8.2-504.jdbc3</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.4.2</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.4.2</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>hsqldb</groupId>
      <artifactId>hsqldb</artifactId>
      <version>1.8.0.7</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
See http://docs.codehaus.org/display/TRAILS/DatabaseConfigurations for other databases.

Update the project classpath:
Code:
mvn test eclipse:eclipse
and refresh the Eclipse project.

Step 2: Reverse engineer the database
Create a new package that will hold the JPA classes.
Right-click on the package and select Import from database. A wizard will be opened.
Select the postgres driver and enter the other JDPC parameters in the wizard and push Next.
Select the "public" database schema and push finish.
An editor will be opened:Image

Save this editor. This will generate Java code for JPA with the default import script.

Step 3: Configuration

Create a new source folder src/main/resources with a directory META-INF.

Create persistence.xml in src/main/resources/META-INF:
Code:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
   version="1.0">
   <persistence-unit name="hrm">
     <provider>org.hibernate.ejb.HibernatePersistence</provider>
   </persistence-unit>
</persistence>
The important thing to notice there is the persistence-unit name "hrm". This will be used in the Java code later.

Create hibernate.properties in src/main/resources:
Code:
# PostgreSQL
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.connection.driver_class=org.postgresql.Driver
hibernate.connection.url=jdbc:postgresql://localhost/hrm
hibernate.connection.username=<username>
hibernate.connection.password=<password>
See http://docs.codehaus.org/display/TRAILS/DatabaseConfigurations for other databases.

Create log4j.properties in src/main/resources:
Code:
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%p %c %m%n

log4j.rootCategory=INFO,console
log4j.logger.net.sf.hibernate.cfg=INFO


Step 4: Create a Java application
Modify the App class that maven has created:
Code:
package com.objectgen.example;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.objectgen.example.data.Company;

public class App
{
    public static void main(String[] args)
    {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("hrm");
        EntityManager em = factory.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        try {
           List<Company> result = em.createQuery("from Company").getResultList();
           for(Company c : result) {
              System.out.println("Company: " + c.getName() +
                    (c.getMainlocationId() != null ? ", main location: " + c.getMainlocationId().getName() : "") );
           }
           tx.commit();
        } catch(RuntimeException e) {
           tx.rollback();
           throw e;
        } finally {
           em.close();
           factory.close();
        }
    }
}
Replace Company with your own imported classes.

Run this class as a Java application. If everything went well, you should see some output from the database.

Step 5: Unit testing
I use HSQLDB for unit testing. This way I can set up a database from scratch in memory for each unit test.

To configure HSQLDB, create a new source directory src/test/resources with a file hibernate.properties:
Code:
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.connection.driver_class=org.hsqldb.jdbcDriver
hibernate.connection.username=sa
hibernate.connection.password=

# HSQLDB in-memory for unit testing
hibernate.connection.url=jdbc:hsqldb:mem:mydatabase

# This will clear all data and create empty tables. That's perfect for unit testing.
# NOTE! Be careful to not use this against a production database!
hibernate.hbm2ddl.auto=create-drop

# Optimize performance for unit tests
hibernate.connection.pool_size=1
hibernate.jdbc.batch_size=1
hibernate.default_batch_fetch_size=1

# For debugging
hibernate.show_sql=true
hibernate.bytecode.use_reflection_optimizer=false
To be sure JUnit uses this hibernate.properties file and not the one in src/main/resources, open Project > Properties, Java Build Path, Source, select the Output folder under src/test/resources and push Edit.Image

Then select Specific output folder and enter target/test-classes.Image

We are now ready to create a unit test:
Code:
package com.objectgen.example.data;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import junit.framework.TestCase;

public class CompanyTest extends TestCase {
   private EntityManagerFactory factory;

   protected void setUp() throws Exception {
      super.setUp();
      factory = Persistence.createEntityManagerFactory("hrm");
   }

   protected void tearDown() throws Exception {
      factory.close();
      super.tearDown();
   }

   public void testListCompanies() throws Exception {
      createCompany("Giggle");
      createCompany("Macrosoft");

      List<Company> companies = listCompanies();
      assertEquals(2, companies.size());
      Company c1 = companies.get(0);
      assertEquals("Giggle", c1.getName());
      assertEquals("HQ", c1.getMainlocationId().getName());
   }

   public void testCreateCompanie() throws Exception {
      assertEquals(0, listCompanies().size());

      createCompany("Giggle");
      assertEquals(1, listCompanies().size());
   }

   /**
    * This is just a demonstration of how to create an object in the database.
    * A container or framework should handle transactions etc.
    */
   public void createCompany(String name) {
      EntityManager em = factory.createEntityManager();
      EntityTransaction tx1 = em.getTransaction();
      tx1.begin();

      Company company1 = new Company();
      company1.setName(name);
      Location location1 = new Location();
      location1.setName("HQ");
      company1.setMainlocationId(location1);
      em.persist(location1);
      em.persist(company1);

      tx1.commit();
   }

   /**
    * This is just a demonstration of how to read objects from the database. A
    * container or framework should handle transactions etc.
    */
   public List<Company> listCompanies() {
      EntityManager em = factory.createEntityManager();
      EntityTransaction tx2 = em.getTransaction();
      tx2.begin();

      List<Company> companies = em.createQuery("from Company").getResultList();

      tx2.commit();
      em.close();

      return companies;
   }
}
Notice that setUp refers to the same persistence-unit name "hrm" as persistence.xml. tearDown will close the factory so that the next unit test setUp creates a completely empty database in memory (thanks to HSQLDB and "hibernate.hbm2ddl.auto=create-drop" in the test hibernate.properties).

The "business methods" createCompany and listCompanies are just examples. In a real application the container or a framework should take care of the EntityManager, transactions, etc.

This tutorial has gone through how to set up a project from scratch and get started with DB Importer. Other posts in this forum show how to configure the imported code.


 
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 1 post ] 

All times are UTC + 1 hour [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
cron
Powered by phpBB © 2002, 2006 phpBB Group