Menu

Tree [d33f10] master /
 History

HTTPS access


File Date Author Commit
 codegen 2012-09-03 Harry Gardner IV Harry Gardner IV [d33f10] Initial check-in of mavenized dal4j project str...
 common 2012-09-03 Harry Gardner IV Harry Gardner IV [d33f10] Initial check-in of mavenized dal4j project str...
 licenses 2012-01-03 unknown unknown [6b1ea9] Initial Check-in
 runtime 2012-09-03 Harry Gardner IV Harry Gardner IV [d33f10] Initial check-in of mavenized dal4j project str...
 samples 2012-09-03 Harry Gardner IV Harry Gardner IV [f8b146] Initial check-in of mavenized dal4j project str...
 README.txt 2012-06-11 Harry Gardner IV Harry Gardner IV [0c7362] updated documentation to accurately reflect how...
 pom.xml 2012-09-03 Harry Gardner IV Harry Gardner IV [d33f10] Initial check-in of mavenized dal4j project str...

Read Me

Introduction
============

Welcome to Data Access Layer for Java (DAL4j) a command line tool and framework 
used to reverse engineer a MySQL or SQLServer database scheama into a set of 
JPA Entity Beans. 

DAL4j can be useful for scenarios where there is an existing database schema
but a technology other that JPA is used by applications to interact with
the database. DAL4j can provide an relatively pain free way to migrate
your code base from other technologies such as JDBC or Hibernate to JPA.
Last, if your preferred method of development is the apply changes to the DB
and then modify code, DAL4j can be useful to you as well. In this case changes
are applied to the DB and the individual Entity Beans that were modified
can be regenerated.

NOTE: Since DAL4j has only been tested with MySQL and SQLServerr, help testing
and integration additional database vendors is needed.  If your preferred 
database type is not supported, please have a look at what DAL4j does, and 
give code generation a try (hacking may be required), there is a chance it
might just work. :) If you havce suggestions or are interested in contributing,
please contact hgiv@yahoo.com with any questions. Thank you!


The follow describes how DAL4j is used: 

1. Configure the database to reverse engineer, including:

   o DB connection information
   o Tables and Views to generate code for
   o Package name of generated Entity Beans
   o Directory to generate Entity Beans to
   o The type of code generation to use, simple or framework.
   o Optional database to java type mappings, use if a type in your database is
     not currently mapped by default by dal4j.

2. Run the dal4j classgen command line tool to automatically connect to 
   the target database and generate JPA Entity Beans for the tables and 
   views found in the configuration file.

   The command line tool that performs is wrapped in scripts that can be found
   in the top level bin directory and the bin directory for all examples, found
   in the samples directory. Usage of this script is:

   classgen[.sh||.bat] [-t table1,table2,etc] configFileName.xml

3. Integrate the generated JPA Entity Beans into your application. The
   generated Entity Beans can be used by a stand alone application,
   EJB, Spring, etc.

4. Manually add entity relationships to the generated pojo's. 

5. Optinally configure relationships added and tested in step 4 to the dal4j 
   XML connfiguration file. This will allow subsequent code genreation runs
   without loosing the entity relationships added in the previous step. 
   The type of information that can be injected into generated pojo's across 
   code generation cycles includes:

   1. imports - global or per generated class.
   2. Class level annotations
   3. Field level annotations
   4. Code such as relationship mappings (hande coded), constants, 
      transient fields, etc.
   5. Injected code can also be added to the generated copy constructor, clone,
      and equals methods.

See samples/round-trip for a working example. 

There are currently two different types of code generators that DAL4j can use
to generate Entity Beans:

  o com.dal4j.jpa.tools.codegen.SimplePojoGenerator - This class generates 
    traditional Entity beans not for use with the DAL4j Framework. One possible
    use of this generator is one-time schema reverse engineering. In this case
    one-to-many or many-to-one associations can be manually added to the
    generated entities and the entities would be manually maintained going 
    forward. 
    
    See samples/simple/README.txt for an example of a project that generates 
    and shows usage of DAL4j Simple Entity Beans. 

    See samples/round-trip/README.txt for ann example of a project that
    generates DAL4j simple Entity Beans and maintains relationships across
    code generation runs.

  o com.dal4j.jpa.tools.codegen.FrameworkPojoGenerator - This class generates
    Entity beans that inherit from the DAL4j framework classes. These beans
    can be used in conjunction with DAL4j framework classes such as EntityDAO<C>
    and DAOFactory. 

    See samples/framework/README.txt for an example of a project that generates 
    and shows usage of DAL4j framework Entity Beans.

Sample Applications
====================
DAL4j ships with sample applications and configurations for code generation
against the sample database. To get started, see samples/README.txt. 

Code Generation
===============
See the README.txt files in samples/simple, samples/framework, or
samples/round-trip to try code generation against the sample database. 

See samples/db/README.txt for instructions describing how to create the sample 
database.

In general, follow these steps to generate code:

1. Locate a template XML configuration file and copy. Sample configuration
   files can be found in:

   bin/config-mysql.xml - MySQL configuration pointing to the sample database.

   bin/config-sqlserver.xml - SQL Server configuration pointing to the sample 
                              database.


   Making a local copy of a configuration file will allow you to change 
   DB connection and tables/views to geneate code for while keeping a golden
   copy of the configuration files available.

2. Edit the copied configuration file and modify DB connection information:

  <url>jdbc:mysql://DB_HOST_HERE/YOUR_DB_HERE</url>
  <user>YOUR_DB_USER_HERE</user> <!-- DB user -->
  <pwd>YOUR_DB_PASSWORD_HERE</pwd> <!-- DB password -->
  <instance>YOUR_DB_NAME_HERE</instance> <!-- DB name -->

3. In the local copy of configuration, specify the tables to generate code for:

   For example, to generate code for a specific set of tables:

  <tables>YOUR_TABLE_1,YOUR_TABLE_2,YOUR_TABLE_3,etc.</tables>

  Alternatively, omitting <tables> will result in code generation for every
  table defined in the database. The <excludeTables> element can be used to
  omit tables from code generation. 

  For example, to generate code for all tables 
  (except DATABASECHANGELOG, DATABASECHANGELOGLOCK):

  <!-- <tables>YOUR_TABLE_1,YOUR_TABLE_2,YOUR_TABLE_3,etc.</tables> -->
  <excludeTables>DATABASECHANGELOG, DATABASECHANGELOGLOCK</excludeTables>

4. In the local copy of configuration, specify views to generate code for:

   For Example:

  <views>
    <view>
      <name>YOUR_VIEW_1</name>
      <primaryKeyColumn>view1_primary_key_column</primaryKeyColumn>
    </view>
    <view>
      <name>YOUR_VIEW_2</name>
      <primaryKeyColumn>view2_primary_key_column</primaryKeyColumn>
    </view>
  </views>

NOTE: The view primary key column is the column that will be annotated with
      @Id and should be a value that uniquely identifies each row in the view.

5. In the local copy of configuration, specify the package name and output
   directory for generated entities:

  <!-- Package name for the generated Entity beans -->
  <pojoPackageName>com.yourdomain.ejb.entity</pojoPackageName>

  <!-- Directory to place generated entity beans -->
  <pojoOutputDirectory>c:/temp/com/yourdomain/ejb/entity</pojoOutputDirectory>

6. In the local copy of configuration, specify the EntityBean code generator 
   to use, i.e.:

  <!-- To Generate EntityBeans that use the DAL4j framework, use: -->
  <pojoCodeGenerator>com.dal4j.jpa.tools.codegen.FrameworkPojoGenerator</pojoCodeGenerator>

  <!-- To Generate Simple EntityBeans that use do not use the framework: -->
  <!-- a.k.a. Plan Old JPA Entities -->
  <pojoCodeGenerator>com.dal4j.jpa.tools.codegen.SimplePojoGenerator</pojoCodeGenerator>

7. Generate the code:

   From the bin directory run:

   Unix/Cygwin: classgen.sh <yourConfigFile.xml>
   DOS: classgen <yourConfigFile.xml>

   See classgen usage for more information.

   Assuming the DB connection, tables, and views were properly configured the
   code should of been generated to the directory specified in the configuration
   file. 

   See samples/framework/README.txt and samples/simple/README.txt for more 
   details.

   IMORTANT NOTE: If code generation fails because a database type mapping is 
   not supported, type mappings can be added to <yourConfigFile.xml>. 
   See 'Defining Data Type Mappings' below for more information.

8. Add relationship mappings to the generated entity beans and test. 

   For example: @OneToMany, @ManyToOne, @ManyToMany

9. Optionally add table or view relationships to the generated entities then
   copy this code into the the dal4j XML configuration file. Doing this will 
   allow the relationships defined in the step above to be maintained across 
   subsequent code generation runs.  

   In addition relationships, the following code artifacts can be automatically
   injected into DAL4j generated entities:

   1. Global imports
   2. Global class annotations
   3. Class imports
   4. Class class annotations
   5. Class code blocks
   6. Addition of injected attributes into equals, clone, and the copy 
      constructor, through a table or view's extraAttributes configruation
      element.
   7. Field level annotations 

   For more information see the 'Code Inection' section of this document or
   the sample/round-trip project.

   Relationship mappings in the XML file are defined as follows:

<entityBeanGenConfig>

  ...

  <relationships>
     <table>
        <name>SOME_TABLE</name>
           <readOnlyColumns>
      <!-- Columns to be annotationed with insertable=false,updatable=false -->
           <readOnlyColumn>COLUMN_NAME1</readOnlyColumn>
           <readOnlyColumn>COLUMN_NAME2</readOnlyColumn>
        </readOnlyColumns>

        <imports>import com.some.package.SomeAnnotation;</imports>
        <classAnnotations>@SomeAnnotation("$ClassName")</classAnnotations>

        <!-- add someObject (injected below) to clone, equals, and copy   -->
        <!-- constructor. extraAttributes is a CSV list: someObj,otherObj -->
        <extraAttributes>someObject</extraAttributes>

        <injectCode><![CDATA[

   // Code to be added when code for SOME_TABLE is generated 
   private SomeObject mSomeObject;

   public void setSomeObject (SomeObject pVal) { mSomeObject = pval; }

   @OneToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)
   @JoinColumn(name="SOME_JOIN_COLUMN_NAME")
   public SomeObject getSomeObject() { return mSomeObject; }

        ]]></injectCode>
      </table>
      <!-- Add additional relationship mapipings here -->

   </relationships>

  <!-- Views with code injection of imports, annotations, and code -->
  <views>

    <!-- View w/out imports, class annotations or code -->
    </view>
      <name>order_view</name>
      <primaryKeyColumn>order_item_id</primaryKeyColumn>
      <imports></imports>
      <classAnnotations></classAnnotations>
      <injectCode><![CDATA[ // Insert code here. ]]></injectCode>
    </view>
    <!-- View with injected imports, class annotations, and code -->
    <view>
      <name>user_view</name>
      <primaryKeyColumn>web_user_id</primaryKeyColumn>
      <imports>
import java.util.List;
import com.dal4j.sample.simple.annotations.SomeAnnotation;
      </imports>
      <classAnnotations>
@SomeAnnotation (name="$ClassName")
      </classAnnotations>
        <!-- add userOrders (injected below) to clone, equals, and copy   -->
        <!-- constructor. extraAttributes is a CSV list: someObj,otherObj -->
        <extraAttributes>userOrders</extraAttributes>
      <injectCode><![CDATA[

   // Optional list of order's that can be manually attached to this class.
   private List<Order> mUserOrders = null;
   public void setUserOrders (List<Order> pOrders) { mUserOrders = pOrders; }
   public List<Order> getUserOrders() { return mUserOrders; }

      ]]></injectCode>
    </view>

  <views>

<entityBeanGenConfig>

See samples/round-trip for a working exmple of this feature.

classgen Usage
==============
classgen is a batch or shell script is used to generate Entity Beans using
an XML configuration file that controls how and where the beans are genreated
to.

The Usage Statement for classgen is:

   classgen [-t table1,table2,etc] configFileName.xml

   -t <tableCSVList> - Optional parameter, used to over-ride the table list
                       configured in configFile.xml. This option can be used
                       to regenerate code for a few tables rather than the 
                       entire list of tables specified in the XML configuration 
                       file.

   -v <viewCSVList> - Option parameter, used to specify which views 
                      code should be generated for.
                      The specified view must be defined in configFile.xml.

   configFileName - The name of the XML configuration file containing the
                    database 

   NOTE: Views specified in -v must be defined in configFile.xml

   TIP: Do not put spaces between table or view CSV lists:
        INCORRECT USAGE: table1, table2
        CORRECT USAGE: table1,table2


Building DAL4j Source Distribution
==================================

Follow these instructures to build the dal4j source distribution.

The top level source directory contains build.xml and build.properties. 

Build.properties should be modified for your enviornment.

#
# Defines the jar containing JPA implementation library, by default
# eclipselink is used.
#
jpa.jar=lib/eclipselink-1.0.2/jlib/jpa/javax.persistence_1.0.0.jar

# Used by the create-and-deploy target, defines location the DAL4j framework
# jar to a directory such as app/web server lib directory.
#
deploy.lib=c:/jboss-5.1.0.GA/server/default/lib

To build
simply run 'ant' in your favorite command line tool from the current directory. The default target, create-all, is called if no target is specified.

Build targets
-------------

create-all : This will build the DAL4j jars and java doc (default target).

create-and-deploy : This will build the DAL4j jars and deploy the DAL4j runtime
                    to the directory specified by deploy.lib from 
                    build.properties.

Build Output
------------

Output from the build process is written to the build directory. The jars
can be found in build/jars.

The jars generated by the build include:

dal4j-0.3.5.jar : This jar contains the DAL4j runtime framework classes. 
                  This jar is only required if framework Entity beans are 
                  generated.

dal4j-0.3.5.javadoc.jar : Contains DAL4j java docs.

dal4j-tools-0.3.5.jar : This jar contains code used to reverse engineer the 
                        database to generate Entity Beans. This jar is used
                        by internal tools and does not need to be deployed.


Defining Data Type Mappings
===========================
There are a default set of database to java type mappings supported by DAL4j.
To add additional types or over-ride how a database type is mappped, the
XML configuration file used to drive code generation can be modified. To
define custom type mappings, add the following to the XML configuration file
between <entityBeanGenConfig> ... </entityBeanGenConfig>.

  <entityBeanGenConfig>

  ...

     <types>
        <type>
           <databaseType>some_db_type</databaseType>
           <javaType>SomeJavaTypeWhichInheritsFromObject</javaType>
        </type>
        <type>
           <databaseType>some_db_type2</databaseType>
           <javaType>SomeJavaTypeWhichInheritsFromObject</javaType>
        </type>
     </types>

  ...

  </entityBeanGenConfig>

If a database type with a specific size should have a mapping defined, define 
it as: db_type(X). Note that type mappings by size of a defined column are 
always resolved before type mappings w/out a size specified. So, it is 
possible to have tinyint(1) and tinyint mappings defined.

Here is an example to map tinyint(1) to a boolean and tinyint to Byte

     <types>
        <type>
           <databaseType>tinyint(1)</databaseType>
           <javaType>Boolean</javaType>
        </type>
        <type>
           <databaseType>tinyint</databaseType>
           <javaType>Byte</javaType>
        </type>
     </types>

NOTE: The tinyint type mappings above are supported by default.

The default type mappings supported by DAL4j are:

      DB_TYPE -> JavaTypeWhichInheritsFromObject

      "varchar" -> "String"
      "char" -> "String"
      "varchar2" -> "String"
      "text" -> "String"
      "int" -> "Integer"
      "int identity" -> "Integer"
      "smallint" -> "Integer"
      "number" -> "Integer"
      "tinyint" -> "Byte"
      "tinyint(1)" -> "Boolean"
      "bit" -> "Boolean"
      "bigint" -> "Long"
      "bigint identity" -> "Long"
      "datetime" -> "Date"
      "date" -> "Date"
      "Time" -> "Date"
      "smalldatetime" -> "Date"
      "timestamp" -> "Date"
      "float" -> "Float"
      "double" -> "Double"
      "decimal" -> "Double"
      "image" -> "byte []"
      "blob" -> "byte []"

Code Injection
==============
It is also possilbe to customize how pojos are generated DAL4j. The following 
code artifacts can be automatically injected into generated entities:

  1. Global imports - Imports added to every generated class.

  2. Global class annotations - Class level annotations added to every 
                                generated class. See Variables below.

  3. Class imports - Imports added to a specific class (table or view)

  4. Class class annotations - Class level annotations added to a 
                               specific class. See Variables below.

  5. Class code blocks - Free form code blocks added to a specific class.

  6. Addition of injected attributes into equals, clone, and the copy 
     constructor. This is done through a table or view's extraAttributes 
     configruation element.

  7. Field level annotations - Use this to annotate on or more fields 
     individually. This can be useful if your entities are serialized
     to XML or JSON to provide additional instructions. 

Code injection is accomplished by modifying the DAL4j XML configuration file. 
Below is a high level example: 


<entityBeanGenConfig>

   ...

   <!-- Global imports and class annotations added to every generated pojo -->
   <imports>import javax.xml.bind.annotation.XmlRootElement;</imports>
   <classAnnotations>@XmlRootElement(name="$ClassName")</classAnnotations>

   <relationships>

      <table>
         <name>SOME_TABLE</name>
         <readOnlyColumns>
            <readOnlyColumn>COLUMN_NAME1</readOnlyColumn>
            <readOnlyColumn>COLUMN_NAME2</readOnlyColumn>
         </readOnlyColumns>
         <classAnnotations>@SomeAnnotation("$ClassName")</classAnnotations>
         <!-- add attributes (found in injectCode below) to clone, equals, -->
         <!-- and the copy constructor. This vairable is a CSV list:       -->
         <!--: i.e.: someAttr, otherAttr, yetAnotherAttr -->
        <extraAttributes></extraAttributes>
         <injectCode><![CDATA[ // Add your code here. ]]></injectCode>

         <!-- Added to SomeTable.java -->
         <imports>
import some.package.SomeAnnotation;
import org.springframework.format.annotation.DateTimeFormat;
         </imports>

       <columnProperties>
         <columnProperty>
	    <!-- The column to be customized -->
            <columnName>COLUMN_NAME1</columnName>
	    <!-- Add the folloiwng annotations to the attribute -->
            <injectFieldAnnotations> 
               @DateTimeFormat(pattern= "y-M-d")
            </injectFieldAnnotations>
            <!-- Add the following annotations to the get method -->
            <injectGetMethodAnnotations>
               @DateTimeFormat(pattern= "y-M-d")
            </injectGetMethodAnnotations>
         </columnProperty>
         <columnProperty>
            <columnName>user_updated_date</columnName>
            <injectFieldAnnotations>
               @DateTimeFormat(pattern= "y-M-d")
            </injectFieldAnnotations>
         </columnProperty>
       </columnProperties>

      </table>

      ...

   </relationships>

   <views>

      <view>
         <name>SOME_VIEW</name>
         <!-- The field that makes a row unique, typically a PK from one of -->
         <!-- the joined tables can be identified as unique.                -->
         <primaryKeyColumn>SOME_PRIMARY_KEY_COLUMN</primaryKeyColumn>
         <!-- Added to SomeView.java -->
         <imports>import som.package.SomeOtherAnnotation</imports>
         <classAnnotations>@SomeOtherAnnotation("$className")</classAnnotations>
         <!-- add attributes (found in injectCode below) to clone, equals, -->
         <!-- and the copy constructor. This vairable is a CSV list:       -->
         <!--: i.e.: someAttr, otherAttr, yetAnotherAttr -->
         <extraAttributes></extraAttributes>
         <injectCode><![CDATA[ // Insert code here. ]]></injectCode>

         <!--
         <columnProperties>
            <columnProperty>
               <columnName>some_column</columnName>
               <injectFieldAnnotations>
                /** @YourAnnotationHere */
               </injectFieldAnnotations>
               <injectGetMethodAnnotations>
                /** @YourAnnotationHere */
               </injectGetMethodAnnotations>
            </columnProperty>
         </columnProperties>
         -->

      </view>

      ...

   <views>

</entityBeanGenConfig>

<classAnnotations> Variables
----------------------------
The <classAnnotations> element allows annotations to be added above a classes
definition. DAL4j provides 4 code injection variables that can affect the
output of an injected <classAnnotations> block. The variables provided include:

$className - The name of the class, first letter lower case.
$ClassName - The name of the class, first letter upper case.
$table_name - The name of the table lower case.
$TABLE_NAME - The name of the table upper case.

For class 'MyClass' generated from table 'CORP_MY_CLASS', the variables would 
have the following values:

$className = myClass
$ClassName = MyClass
$table_name = corp_my_class
$TABLE_NAME = CORP_MY_CLASS

Usage:

<classAnnotations>@SomeAnnotation("$ClassName")</classAnnotations>

Would Render as:

@SomeAnnotation("MyClass")
public class MyClass extends java.io.Serializable
{
...

License
=======
DAL4j is licensed under GNU Lesser General Public License, see 
licenses/DAL4j-license.txt for more infomration. DAL4j is distributed in the 
hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
GNU Lesser General Public License for more details. 

Copyright 2011,2012 Harry Gardner IV
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.