Kleber Mota
Kleber Mota

Reputation: 9095

Using Hibernate to save/restore data from a database (postgresql)

In my project, I just generate the pojo and dao classes with the hibernate. But the dao classes generated by Hibernate are all in this style:

package com.ligadesportiva.data;

// Generated 14/03/2014 22:39:34 by Hibernate Tools 3.4.0.CR1

import java.util.List;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.ligadesportiva.core.Jogador;

/**
 * Home object for domain model class Jogador.
 * @see com.ligadesportiva.data.Jogador
 * @author Hibernate Tools
 */
public class JogadorHome {

    private static final Log log = LogFactory.getLog(JogadorHome.class);

    private final SessionFactory sessionFactory = getSessionFactory();

    protected SessionFactory getSessionFactory() {
        try {
            return (SessionFactory) new InitialContext()
                    .lookup("SessionFactory");
        } catch (Exception e) {
            log.error("Could not locate SessionFactory in JNDI", e);
            throw new IllegalStateException(
                    "Could not locate SessionFactory in JNDI");
        }
    }

    public void persist(Jogador transientInstance) {
        log.debug("persisting Jogador instance");
        try {
            sessionFactory.getCurrentSession().persist(transientInstance);
            log.debug("persist successful");
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void attachDirty(Jogador instance) {
        log.debug("attaching dirty Jogador instance");
        try {
            sessionFactory.getCurrentSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void attachClean(Jogador instance) {
        log.debug("attaching clean Jogador instance");
        try {
            sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void delete(Jogador persistentInstance) {
        log.debug("deleting Jogador instance");
        try {
            sessionFactory.getCurrentSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    public Jogador merge(Jogador detachedInstance) {
        log.debug("merging Jogador instance");
        try {
            Jogador result = (Jogador) sessionFactory.getCurrentSession()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public Jogador findById(int id) {
        log.debug("getting Jogador instance with id: " + id);
        try {
            Jogador instance = (Jogador) sessionFactory.getCurrentSession()
                    .get("com.ligadesportiva.data.Jogador", id);
            if (instance == null) {
                log.debug("get successful, no instance found");
            } else {
                log.debug("get successful, instance found");
            }
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List findByExample(Jogador instance) {
        log.debug("finding Jogador instance by example");
        try {
            List results = sessionFactory.getCurrentSession()
                    .createCriteria("com.ligadesportiva.data.Jogador")
                    .add(Example.create(instance)).list();
            log.debug("find by example successful, result size: "
                    + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }
}

But I want data be saved/read from a postgresql database. Is there any code I should add to this project for make this dao classes interact with my DB?

Upvotes: 1

Views: 1343

Answers (1)

Kleber Mota
Kleber Mota

Reputation: 9095

Just for the record, I am put here some considerations about this subject I learn there few days:

First all, besides the two sets of classes generated by Hibernate (DAO and POJO), I create one anotherm based in this example:

http://www.baeldung.com/hibernate-4-spring

where I configure some options and methods of the Hibernate and point to the file where I place the options for conect to the database (database.properties).

After, I made some changes in the generated classes:

1) In the POJO class, I added the annotation @Entity and @Table for the class (and the second annotation with de parameter value="?", where ? is the name of the table associated to this class). For the attributes, I add the annotation @Column for all of them and the annotation @Id for the attribute related to the primary key.

2) In the DAO classes, I added the annotation @Repository for the class, and the annotation @Transactional for all the methods. Because of this annotation, I may insert in my *-servlet.xml file the follow line:

<tx:annotation-driven transaction-manager="transactionManager"/>

and in the header, this options:

xmlns:tx="http://www.springframework.org/schema/tx"

and inside xsi:schemaLocation:

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd.

Also, the atribute sessionFactory was annotated with @Autowired, the association was removed, and this methos was added:

protected Session getCurrentSession() {
    return sessionFactory.getCurrentSession();
}

For use of this class to handle the queries to database, I add them as atributes of the controller, always informing the annotation @Autowired.

Inside each method of the controller, I use the classes as this examples:

read data

Usuario novo = usuario.findById(this.getId_usuario());

save data

Sessao nova = new Sessao(novo, 0);
sessao.persist(nova);

Upvotes: 1

Related Questions