How to create a generic DAO for CRUD methods



I’m trying to create a generic DAO for the basic CRUD methods so that I can reuse the code, but I really have no clue how to start.

I already have a DAO for every class, and they work perfectly.

I read lots of tutorial, and downloaded projects, but I can’t adapt (or understand) it to my program.

Here is my class:

public class Cliente {
    private String nombre, direccion, telefono, cuit;
    private int codigo, codigoPostal;
    private double saldo, deuda;

    public Cliente(String nombre, String direccion, int codigoPostal, String telefono, String cuit) {
        this.nombre = nombre;
        this.direccion = direccion;
        this.codigoPostal = codigoPostal;
        this.telefono = telefono;
        this.cuit = cuit;
        this.saldo = 0;
        this.deuda = 0;
    }
    
    public Cliente(){
    }
    
    //all the getters and setters

This is my GenericDAO that is not working

public class GenericDAO {
    
    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;

    public <T> T save(final T o){
      return (T) sessionFactory.getCurrentSession().save(o);
    }


    public void delete(final Object object){
      sessionFactory.getCurrentSession().delete(object);
    }

    /***/
    public <T> T get(final Class<T> type, final long id){
      return (T) sessionFactory.getCurrentSession().get(type, id);
    }

    /***/
    public <T> T merge(final T o)   {
      return (T) sessionFactory.getCurrentSession().merge(o);
    }

    /***/
    public <T> void saveOrUpdate(final T o){
      sessionFactory.getCurrentSession().saveOrUpdate(o);
    }

    public <T> List<T> getAll(final Class<T> type) {
      final Session session = sessionFactory.getCurrentSession();
      final Criteria crit = session.createCriteria(type);
     return crit.list();
    }
    
}

My Class.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>
    <class name="principal.Cliente" table="Cliente">
        <id name="codigo" column="codigo">
            <generator class="identity" />
        </id>
        <property name="nombre" type="string" column="nombre"/>
        <property name="direccion" type="string" column="direccion"/>
        <property name="telefono" type="string" column="telefono"/>
        <property name="cuit" type="string" column="cuit"/>
        <property name="codigoPostal" type="int" column="cp"/>
        <property name="saldo" type="double" column="saldo"/>
        <property name="deuda" type="double"  column="deuda"/> 
    </class>
</hibernate-mapping>

This is my HibernateUtil:

public class HibernateUtil {

    private static SessionFactory sessionFactory = buildSessionFactory();
 
    private static SessionFactory buildSessionFactory()
    {
      try
      {
         if (sessionFactory == null)
         {
            Configuration configuration = new Configuration().configure(HibernateUtil.class.getResource("/hibernate.cfg.xml"));
            StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
            serviceRegistryBuilder.applySettings(configuration.getProperties());
            ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
         }
         return sessionFactory;
      } catch (Throwable ex)
      {
         System.err.println("Initial SessionFactory creation failed: " + ex);
         throw new ExceptionInInitializerError(ex);
      }
    }
 
    public static SessionFactory getSessionFactory()
    {
      return sessionFactory;
    }
 
    public static void shutdown()
    {
      getSessionFactory().close();
    }

And my 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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/basededatosprueba</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>
    
        <mapping resource="mapeos/Cliente.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

I’d appreciate if someone could explain how to make it work.

Answer

Solution by duffymo

Use the Spring Boot CrudRepository: spring.io/guides/gs/accessing-data-jpa



Source: stackoverflow