Hibernate +jpa

3 respostas
Malachai

Pessoal,

Tenhi visto muito falarem sobre hibernate + JPA, mas nao to conseguindo ver o porque de colocar o JPA se ja existe o hibernate. Com o hibernate, nos temos os DTOs e os objetos mapeados no hibernate.cfj.xml e os hbs, pra que preciso do JPA? onde posso achar um exemplo de uma arquitetura usando JPA e hibernate?

abs!

3 Respostas

goofed

Tenho a mesma identica dúvida!

rafaelglauber

leiam um pequeno artigo que tem aqui: http://blog.marcomendes.com/category/tecnologias-java/j2ee/

e depois vão perceber que o JPA na verdade é um padrão, e quando usamos o hibernate com anotações por exemplo estamos aplicando o JPA com o Hibernate.

ps. no próprio texto fala que o JPA foi baseado fortemente nas especificações do HIbernate.

fabiojwalter

Utilizamos JPA no Hibernate Annotation, onde não é mais preciso parametrizar .hbm's .xml e todos os outros . que existirem. Apenas o Hibernate.cfg.xml, que será onde indicaremos os caminhos das classes beans.

Nos beans toda descrição de tabelas e de campos do banco é feita usando Annotation, segue abaixo um exemplo de bean e DAO generico para persistir qualquer tipo de objeto.

Este é um BEAN com ANNOTATION gerada automaticamento pelo NetBeans
/*
 * Cidade.java
 *
 * Created on September 8, 2007, 3:41 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package beans;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 * Entity class Cidade
 * 
 * @author Fabio
 */
@Entity
@Table(name = "cadcid")
@NamedQueries( {
        @NamedQuery(name = "Cidade.findByTodos", query = "SELECT c FROM Cidade c"),
        @NamedQuery(name = "Cidade.findByCidId", query = "SELECT c FROM Cidade c WHERE c.cidId = :cidId"),
        @NamedQuery(name = "Cidade.findByCidNome", query = "SELECT c FROM Cidade c WHERE c.cidNome = :cidNome"),
        @NamedQuery(name = "Cidade.findByCidUf", query = "SELECT c FROM Cidade c WHERE c.cidUf = :cidUf"),
        @NamedQuery(name = "Cidade.findByCidSituacao", query = "SELECT c FROM Cidade c WHERE c.cidSituacao = :cidSituacao")
    })
public class Cidade implements Serializable {

    @Id
    @Column(name = "CID_ID", nullable = false)
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer cidId;

    @Column(name = "CID_NOME", nullable = false)
    private String cidNome;

    @Column(name = "CID_UF", nullable = false)
    private String cidUf;

    @Column(name = "CID_SITUACAO")
    private Short cidSituacao;
    
    /** Creates a new instance of Cidade */
    public Cidade() {
    }

    /**
     * Creates a new instance of Cidade with the specified values.
     * @param cidId the cidId of the Cidade
     */
    public Cidade(Integer cidId) {
        this.cidId = cidId;
    }

    /**
     * Creates a new instance of Cidade with the specified values.
     * @param cidId the cidId of the Cidade
     * @param cidNome the cidNome of the Cidade
     * @param cidUf the cidUf of the Cidade
     */
    public Cidade(Integer cidId, String cidNome, String cidUf) {
        this.cidId = cidId;
        this.cidNome = cidNome;
        this.cidUf = cidUf;
    }

    /**
     * Gets the cidId of this Cidade.
     * @return the cidId
     */
    public Integer getCidId() {
        return this.cidId;
    }

    /**
     * Sets the cidId of this Cidade to the specified value.
     * @param cidId the new cidId
     */
    public void setCidId(Integer cidId) {
        this.cidId = cidId;
    }

    /**
     * Gets the cidNome of this Cidade.
     * @return the cidNome
     */
    public String getCidNome() {
        return this.cidNome;
    }

    /**
     * Sets the cidNome of this Cidade to the specified value.
     * @param cidNome the new cidNome
     */
    public void setCidNome(String cidNome) {
        this.cidNome = cidNome;
    }

    /**
     * Gets the cidUf of this Cidade.
     * @return the cidUf
     */
    public String getCidUf() {
        return this.cidUf;
    }

    /**
     * Sets the cidUf of this Cidade to the specified value.
     * @param cidUf the new cidUf
     */
    public void setCidUf(String cidUf) {
        this.cidUf = cidUf;
    }

    /**
     * Gets the cidSituacao of this Cidade.
     * @return the cidSituacao
     */
    public Short getCidSituacao() {
        return this.cidSituacao;
    }

    /**
     * Sets the cidSituacao of this Cidade to the specified value.
     * @param cidSituacao the new cidSituacao
     */
    public void setCidSituacao(Short cidSituacao) {
        this.cidSituacao = cidSituacao;
    }

    /**
     * Returns a hash code value for the object.  This implementation computes 
     * a hash code value based on the id fields in this object.
     * @return a hash code value for this object.
     */
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (this.cidId != null ? this.cidId.hashCode() : 0);
        return hash;
    }

    /**
     * Determines whether another object is equal to this Cidade.  The result is 
     * <code>true</code> if and only if the argument is not null and is a Cidade object that 
     * has the same id field values as this object.
     * @param object the reference object with which to compare
     * @return <code>true</code> if this object is the same as the argument;
     * <code>false</code> otherwise.
     */
    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Cidade)) {
            return false;
        }
        Cidade other = (Cidade)object;
        if (this.cidId != other.cidId && (this.cidId == null || !this.cidId.equals(other.cidId))) return false;
        return true;
    }

    /**
     * Returns a string representation of the object.  This implementation constructs 
     * that representation based on the id fields.
     * @return a string representation of the object.
     */
    @Override
    public String toString() {
       // return "beans.Cidade[cidId=" + cidId + "]";
       return this.getCidId()+" - "+this.getCidNome();
    }
    
}
No exemplo acima a SQL utilizada para gerar a tabela CIDADE foi
CREATE TABLE `cadcid` (
  `CID_ID` int(11) NOT NULL auto_increment,
  `CID_NOME` varchar(70) NOT NULL,
  `CID_UF` varchar(2) NOT NULL,
  `CID_SITUACAO` decimal(2,0) default NULL,
  PRIMARY KEY  (`CID_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Este é um DAO GENERICO para persistir, excluir, alterar, listar e buscar qualquer objeto anotado e persitido no banco de dados
package dao;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;

/**
 *
 * @author fjwalter
 */
public class DAO {
    
    private SessionFactory sf;
    
    public DAO() {
        sf = new AnnotationConfiguration().configure().buildSessionFactory();
    }
    
    public boolean inserir(Object obj){
        Session ss = sf.openSession();
        Transaction trx = ss.beginTransaction();
        boolean ok = false;
        try {
            ss.save(obj);
            trx.commit();
            ok = true;
            ss.close();
        } catch (HibernateException ex) {
            trx.rollback();
            System.out.println("Erro ao Gravar %%%%%%%%%%%%%%%%%%%%%%%%%%");
            ex.printStackTrace();
            ss.close();
        }
        return ok;
    }
    
    public boolean deletar(Object obj){
        Session ss = sf.openSession();
        Transaction trx = ss.beginTransaction();
        boolean ok = false;
        try {
            ss.delete(obj);
            trx.commit();
            ss.close();
            ok = true;
        } catch (HibernateException ex) {
            trx.rollback();
            System.out.println("Erro ao Deletar %%%%%%%%%%%%%%%%%%%%%%%%%%");
            ex.printStackTrace();
            ss.close();
        }
        return ok;
    }
    
    public boolean atualizar(Object obj){
        Session ss = sf.openSession();
        Transaction trx = ss.beginTransaction();
        boolean ok = false;
        try {
            ss.update(obj);
            trx.commit();
            ok = true;
            ss.close();
        } catch (HibernateException ex) {
            trx.rollback();
            System.out.println("Erro ao Gravar %%%%%%%%%%%%%%%%%%%%%%%%%%");
            ex.printStackTrace();
            ss.close();
        }
        return ok;
    }
    //----------------------------------------------------------------------
    public Object busca(Object obj, Integer id) {
        Session session = sf.openSession();
        Transaction trx = session.beginTransaction();
        Object obj2 = session.get(obj.getClass(),id);
        session.flush();
        trx.commit();
        session.close();
        return obj2;
    }
    
    public List listaTodos(String nameQuery){
        Session session = sf.openSession();
        Transaction trx = session.beginTransaction();
        Query q = session.getNamedQuery(nameQuery);
        List resultado = q.list();
        trx.commit();
        session.close();
        return resultado;
    }
}

Estou utilizando MySQL + NetBeans 5.5.1 + HibernateAnnotation + JWS

Qualquer duvida poste um novo topico que tento lhe ajudar

Espero ter ajudado

Criado 10 de outubro de 2007
Ultima resposta 14 de out. de 2007
Respostas 3
Participantes 4