Click here to Skip to main content
Click here to Skip to main content

Simplified ORM with NW.ORM

, 29 Oct 2013
Rate this:
Please Sign up or sign in to vote.
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 

    @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 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:

    // 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.

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

    REntityManager provides basic CRUD for all entities:

    // Create Sample Entity RAUdit
    RAudit ra = new RAudit();
    ra.setSourceMachine("mac");
    rm.create(ra);
    rm.update(ra); 
    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.

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

    Sample query by HQL:

    // 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:

    // 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.

    // 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).

    // 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)

    Share

    About the Author

    Ogwara Rowland
    Software Developer (Senior)
    Nigeria Nigeria
    No Biography provided
    Group type: Organisation (No members)


    Follow on   Twitter   LinkedIn

    Comments and Discussions

     
    -- There are no messages in this forum --
    | Advertise | Privacy | Mobile
    Web02 | 2.8.140821.2 | Last Updated 29 Oct 2013
    Article Copyright 2013 by Ogwara Rowland
    Everything else Copyright © CodeProject, 1999-2014
    Terms of Service
    Layout: fixed | fluid