April 26, 2024

POJO and Hibernate

Hibernate uses the Plain Old Java Object (POJO) programming model to represent database tables in memory. The columns of the table are represented by the fields of the java class. The class-to-table, field-to-column information is kept in XML files. Let’s see how to map the database table object to the Java POJO object. Suppose we want to represent a hypothetical “Customer” for a business domain model.

SOURCE CODE (/giuseu/struts-mvc)

GIT
git clone https://gitlab.com/giuseppeurso-eu/struts-mvc

First of all, we create the customer DB table

$ mysql -uroot -proot

>  USE demodb;
>  CREATE TABLE `customer` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    `lastname` varchar(45) DEFAULT NULL,
    `name` varchar(45) DEFAULT NULL,
    `address` varchar(45) DEFAULT NULL,
    `city` varchar(45) DEFAULT NULL,
    PRIMARY KEY (`id`) USING BTREE
  );

mysql> show tables;
+------------------+
| Tables_in_demodb |
+------------------+
| customer         |
+------------------+
1 row in set (0.00 sec)

mysql> describe customer;
+----------+------------------+------+-----+---------+----------------+
| Field    | Type             | Null | Key | Default | Extra          |
+----------+------------------+------+-----+---------+----------------+
| id       | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| lastname | varchar(45)      | YES  |     | NULL    |                |
| name     | varchar(45)      | YES  |     | NULL    |                |
| address  | varchar(45)      | YES  |     | NULL    |                |
| city     | varchar(45)      | YES  |     | NULL    |                |
+----------+------------------+------+-----+---------+----------------+

Create the customer POJO
– Customer

package com.demo.domain;

public class Customer{

	private Long id;
	private String name;
	private String lastname;
	private String address;
	private String city;

	public Customer(){

	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getLastname() {
		return lastname;
	}

	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

}

Create the hibernate Customer.hbm.xml mapping

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.demo.domain">
  <class name="Customer" table="customer">
  		   <id name="id" column="id">
            <generator class="native"/>
 		  </id>
 		  <property name="name"/>
 		  <property name="lastname"/>
 		  <property name="address"/>
 		  <property name="city"/>	  
  </class>
</hibernate-mapping>

Define the POJO’s mapping resource in hibernate.cfg.xml file

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"       
 		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/demodb</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="connection.pool_size">1</property>

        <!-- POJO's mapping -->
        <mapping resource="com/demo/domain/Customer.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

 

Create the customer DAO interface and its implementation

– CustomerDAO

package com.demo.persistence;

import com.demo.domain.Customer;
import com.demo.hibernate.GenericDAO;

public interface CustomerDAO extends GenericDAO<Customer, Long> {
}

 – CustomerHibernateDAO

package com.demo.persistence;

import org.hibernate.criterion.Restrictions;

import com.demo.domain.Customer;
import com.demo.hibernate.GenericHibernateDAO;

public class CustomerHibernateDAO  extends  GenericHibernateDAO<Customer, Long> implements  CustomerDAO {

	/**
	 * An Example of a customized query to retrieve a customer by name
	 * @param name
	 * @return
	 */
	public Customer findByName(String name){
		 return  (Customer)getSession().createCriteria(Customer.class).add( Restrictions.eq("name",name)).uniqueResult(); 
	 }

}

 

Update the Hibernate Factory layer to get the customer’s DAO

 – DAOFactory

package com.demo.hibernate;

import com.demo.persistence.CustomerDAO;

public abstract class DAOFactory {

    public static final Class HIBERNATE = DAOHibernateFactory.class;

    public static DAOFactory instance(Class factory) {
        try {
            return (DAOFactory)factory.newInstance();
        } catch (Exception ex) {
            throw new RuntimeException("Couldn't create DAOFactory: " + factory);
        }
    }

    // Add your DAO interfaces here
    public abstract CustomerDAO getCustomerDAO();

}

 

– DAOHibernateFactory 

package com.demo.hibernate;

import org.hibernate.Session;

import com.demo.persistence.CustomerDAO;
import com.demo.persistence.CustomerHibernateDAO;

public class DAOHibernateFactory extends DAOFactory {

    private GenericHibernateDAO instantiateDAO(Class daoClass) {
        try {
            GenericHibernateDAO dao = (GenericHibernateDAO)daoClass.newInstance();
            dao.setSession(getCurrentSession());
            return dao;
        } catch (Exception ex) {
            throw new RuntimeException("Can not instantiate DAO: " + daoClass, ex);
        }
    }

    // You could override this if you don't want SessionUtil for lookup
    protected Session getCurrentSession() {
        return SessionUtil.getSessionFactory().getCurrentSession();
    }

    // Add your DAO here
    public CustomerDAO getCustomerDAO() {
		return (CustomerDAO)instantiateDAO(CustomerHibernateDAO.class);
	}

}

Here the project layout

pojo-hibernate-project-layout

 

Related posts

Leave a Reply

Your email address will not be published.