Click here to Skip to main content
15,885,278 members
Articles / Database Development / MySQL

Simplified ORM with NW.ORM

Rate me:
Please Sign up or sign in to vote.
4.33/5 (3 votes)
29 Oct 2013CPOL3 min read 15.5K   6  
NW.ORM, a helper framework for working Hibernate.

Table of Contents

Introduction

While implementing software that has to do with databases, the following actions usually occur for a typical Java developer (like me) working with hibernate .

  • Add hibernate dependencies
  • Create Required Entities
  • Add entity mappings to the configuration file
  • Implement a Session Factory Builder
  • Implement a Service Layer for Querying the system (Possibly DAOs for each entity)
  • Implement CRUD methods on the service layer
  • Start coding the application.....

The problem was not in the number of things to do, but in the level of repetition required each time a new project comes up. Also, multiple developers projects usually tend towards varying implementations, with each developer handling database session as they see best. While working with multiple databases, will require developers to re-implement some aspect of the system.

NW.ORM aims at simplifying access to databases by creating a uniform and reusable approach to implementing software that requires database access. Providing developers more time to focus on the actual project work. The framework uses hibernate libraries underneath for database transactions.

What NW.ORM Provides

  • Single interface for all database transactions. Multiple Data Access Objects are not required
  • Work with multiple databases in the same application at the same time
  • Query using Hibernate Criteria, HQL or SQL
  • Support for JPA based and HBM file based configurations
  • Returns appropriate class objects without casting
  • Provides mapped super classes for quick creation of JPA based entities

How to Use

To use the framework:

  • Get the latest version from https://sourceforge.net/projects/nw-orm/files/
  • Add dependencies to your project
  • Dependencies

    NW.ORM has the following dependencies:

    • Hibernate Framework
    • Neemworks Commons
    • Slf4j Logger

    Hibernate and slf4j dependencies can be downloaded from their respective websites while Neemworks commons is available on NW.ORM sourceforge files directory.

    Setup Dev Environment

    Simply add NW.ORM jar file with dependencies to your project classpath.

    With project classpath properly set up, actual usage can start. Basically, to start working with the database, it is typical to start with creating necessary entity objects. Instead of creating from scratch, one can extend either REntity object or IEntity. REntity provides a UUID based primary key, while IEntity provides a Long type primary key. It also provides me certain methods like ability to get the target database TABLE (which does not necessarily need to match the object name) name at runtime. See snippet below.

    Defining and Mapping Entities 

    Java
    @Entity
    @Table(name = "ACCESS_TOKEN")
    public class AccessToken extends REntity {
    
    	private static final long serialVersionUID = -5221279551618337736L;
    }

    All entities must be mapped in the hibernate configuration file as required by hibernate. Multiple configurations are allowed in cases where multiple databases needs to be accessed. Below is a sample configuration file for working with a PostgreSQL database, with 4 entities mapped.

    XML
     <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
        <session-factory>
            <property name="hibernate.show_sql">false</property>
            <property name="hibernate.format_sql">false</property>
            <property name="use_sql_comments">false</property>
      <property name="hbm2ddl.auto">update</property>
    	  <property name="show_sql">false</property>
    
            <property name="hibernate.dialect">
            org.hibernate.dialect.PostgreSQLDialect</property>
            <property name="hibernate.connection.driver_class">
            org.postgresql.Driver</property>
         	 <property name="hibernate.connection.url">
         	 jdbc:postgresql://localhost:5432/**db</property>
            <property name="hibernate.connection.username">**d**</property>
    	 <property name="hibernate.connection.password">*minds</property>
    
    	 <property name="hibernate.c3p0.min_size">5</property>
    	 <property name="hibernate.c3p0.max_size">30</property> <!-- seconds -->
    	 <property name="hibernate.c3p0.timeout">1800</property>
    	 <property name="hibernate.c3p0.max_statements">50</property>
    
            <!-- add classes to map from here -->
            <mapping class="com.nw.napi.model.NUser" />
            <mapping class="com.nw.napi.model.NimblarClient" />
            <mapping class="com.nw.napi.model.AccessToken" />
            <mapping class="com.nw.napi.model.ReleaseNotificationRequest" />
        </session-factory>
    </hibernate-configuration>

    For none JPA based configuration (i.e., hbm based configuration), all that is required is to add the appropriate hibernate configuration file in the classpath.

    Querying

    At this point, to initialize the service layer for a particular database with configuration file name hibernate.cfg.xml. An instance of REntityManager is required as shown below:

    Java
    // Create an instance
    REntityManager rm = REntityManager.getInstance("hibernate.cfg.xml");  

    The same can be repeated if multiple database configuration is required. See the code snippet below for another configuration using the configuration file text.cfg.xml.

    Java
    // Create an instance
    REntityManager rmText = REntityManager.getInstance("text.cfg.xml"); 

    REntityManager provides basic CRUD for all entities:

    Java
    // Create Sample Entity RAUdit
    RAudit ra = new RAudit();
    ra.setSourceMachine("mac");
    rm.create(ra);
    Java
    rm.update(ra); 
    Java
    rm.remove(ra);

    Sample methods for querying the database are shown below:

    Query a table where the column sourceMachine has a value of mac, the method takes a result class to enable appropriate return types.

    Java
     // Find By Criteria
    RAudit audit = rm.getByCriteria(RAudit.class, Restrictions.eq("sourceMachine", "mac"));
    System.out.println(audit.getSourceMachine()); 

    Sample query by HQL:

    Java
    // Find By HQL
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("sa", "mac");
    RAudit audit2 = rm.getByHQL("FROM RAudit r where 
    r.sourceAddress = :sa", parameters, RAudit.class);
    System.out.println(audit2.getSourceMachine()); 

    List results can be returned using getListxxxxxx methods, as shown below:

    Java
    // Find All List
    List<RAudit> laudits = rm.getListByCriteria(RAudit.class);
    
    // Find List by conditions
    List<RAudit> lauditsc = rm.getListByCriteria(RAudit.class, 
    Restrictions.eq("sourceMachine", "mac"), 
    Restrictions.eq("sourceMachinePublic", "mac"));

    Querying by Criteria

    Various criteria can be constructed as required and passed to the get by criteria query method. This method can take any number of restrictions as allowed by Java varargs.

    Java
    // Find By Criteria
    RAudit audit = rm.getByCriteria(RAudit.class, Restrictions.eq
    ("sourceMachine", "mac"), Restrictions.eq("sourceMachineId", "23-A"));
    System.out.println(audit.getSourceMachine());

    Querying By HQL

    Querying by HQL is implemented using the getByHQL methods, parameters are specified as entries in a hashmap (parameter name and value).

    Java
    // Find By HQL
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("sa", "mac");
    RAudit audit2 = rm.getByHQL("FROM RAudit r 
    where r.sourceAddress = :sa", parameters, RAudit.class);
    System.out.println(audit2.getSourceMachine()); 

    License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below.

    License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


    Written By
    Software Developer (Senior) Neemworks Ltd
    Nigeria Nigeria
    This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.
    This is a Organisation (No members)


    Comments and Discussions

     
    -- There are no messages in this forum --