Agosto 24, 2019

POJO e Hibernate esempio pratico

Hibernate usa una modellazione basata su oggetti Plain Old Java Object (POJO) per interagire con il database. Le colonne di una tabella sono rappresentate dagli attributi di una classe java e la gestione del mapping verso le tabelle di database relazionale è delegata a file xml. In questo articolo viene mostrato come mappare il POJO di un ipotetico cliente (Customer) su Hibernate. Viene utilizzato il progetto di esempio mostrato qui.

SOURCE CODE (/giuseu/struts-mvc)

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

Creiamo la tabella Customer sul DB

$ 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    |                |
+----------+------------------+------+-----+---------+----------------+

Creiamo l’oggetto 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;
	}

}

Creiamo il file di mapping hibernate Customer.hbm.xml

<?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>

Definiamo la risorsa utilizzata per il mapping nel file di configurazione hibernate.cfg.xml

<?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>

 

Creiamo per il POJO l’interfaccia DAO e la sua implementazione

– 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(); 
	 }

}

 

Aggiorniamo la Hibernate Factory per recuperare il DAO legato POJO

 – 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);
	}

}

 Ecco come si presenta il layout di progetto

pojo-hibernate-project-layout

 

Related posts

Leave a Reply

Your email address will not be published.