Como o Hibernate funciona?

11 respostas
P

O Hibernate faz o mapeamento de meu DB para um Objeto, certo???

E quando eu faço um Update no objeto persistente ele também altera no meu DB???

Tipo:

session = SessionFactory.currentSession();
session.update(meuobjeto);
session.flush();

Ele também faz o opdate no meu DB???

As outras manipulações de dados(INSERT, DELETE), seguem o raciocinio acima???

Obrigado.

[size=“11”][color=“red”]* Editado: Lembre-se de utilizar BBCode em seus códigos - Reifel[/color][/size] :joia:

11 Respostas

B

perfeitamente.

P

Então posso fazer o seguinte.

O usuário entra na página index.jsp e vê a lista de usuários.
Essa lista eu pego utilizando o seguinte código.

session = SessionFactory.currentSession(); Query query = session .createQuery("select Users from net.mycompany.user.Users Users order by Users.loginuser"); return query.list();

E salvo a lista na sessão. Como faço isso???

Para pegar o usuário:

session = SessionFactory.currentSession(); return (Users) session.load(Users.class, id);

Para fazer a manipulação de dados(UPDATE, DELETE), pego o usuário da lista e utilizo:

session = SessionFactory.currentSession(); session.update(user); session.flush();

Dai ele vai fazer a alteração dos dados que fiz no objeto persistente no meu DB??? Certo???

B

Isso mesmo.

Você vai ter a lista de users e poderá acessá-los assim

Não entendi o porque da sua dúvida… é tudo isso que você disse memso!

P

Quando vou pegar o usuário:

session = SessionFactory.currentSession(); Users user = (Users) session.load(Users.class, id); return user;

Ele responde a seguinte erro:

Desculpe, mas estáva acontecendo esse erro e queria ter certeza que estava fazendo a coisa certa.

Ainda sou um aprendiz.

Obrigado.

B

coloca um break point e ve se ele está pegando mesmo a sessão

P

É a sessão está null.

Mas quando eu peguei a lista:

session = SessionFactory.currentSession(); Query query = session.createQuery("select Users from net.mycompany.user.Users Users order by Users.loginuser"); return query.list();

Porque a sessão está null???

Tenho que salva-la???

B

Ve se te ajuda!!

import cirrus.hibernate.*;
import java.util.Date;

public class AmigoDAO{

    private SessionFactory factory;

    public AmigoDAO() throws Exception{
        Datastore datastore = Hibernate.createDatastore();
        datastore.storeClass(Amigo.class);
        factory = datastore.buildSessionFactory();
    }
    
    public void insert(Amigo amigo) throws Exception{
        Session session = factory.openSession();
        session.save(amigo);
        session.flush();
        session.close();
    }
    
    public java.util.List getList(String condicao) throws Exception{
        Session session = factory.openSession();
        List amigos = session.find(condicao);
        session.flush();
        session.close();
        return amigos;
    }
    
    public Amigo retrieve(String pk) throws Exception{
        Session session = factory.openSession();
        Amigo amigo = (Amigo)session.load(Amigo.class, pk);
        session.flush();
        session.close();
        return amigo;
    }
    
    public void delete(Amigo amigo) throws Exception{
        Session session = factory.openSession();
        session.delete(amigo);
        session.flush();
        session.close();
    }
}

Copiado de http://www.guj.com.br/java.tutorial.artigo.125.4.guj

P

Não tenho esse código na minha classe:

Datastore datastore = Hibernate.createDatastore(); 
        datastore.storeClass(Amigo.class); 
        factory = datastore.buildSessionFactory();

Tenho de implementa-lo???

O Hibernate que tenho é o 2.

P

A classe acima com o exemplo que tem no endereço foi feita na versão 1.2.4 o Hibernate que estou usando é o 2.1.7.

Fui importar esse pacote:
import cirrus.hibernate.*;

E não achou o jar dele.

Como vc faz com suas classes???

Vc tem algum exemplo com o Hibernate 2???

Obrigado.

B

Assim que usamos aqui na empresa.

import java.io.Serializable;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.hibernate.Criteria;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.expression.Expression;
import net.sf.hibernate.expression.Order;
import net.sf.hibernate.mapping.Column;
import net.sf.hibernate.mapping.Component;
import net.sf.hibernate.mapping.PersistentClass;
import net.sf.hibernate.mapping.Property;
import net.sf.hibernate.type.Type;
import br.com.vixteam.framework.integration.data.DataAccessException;
import br.com.vixteam.framework.system.factory.FactoryBase;

/**
 * Classe de Gerenciamento do Mecanismo de Persistência.
 */
public abstract class RootDAO {

    private Transaction transaction;
    
	protected static Map sessionFactoryMap = new HashMap();
	protected static ThreadLocal threadedSessions = new ThreadLocal();
	protected static Configuration cfg;

	/**
	 * Configure the session factory by reading hibernate config file
	 */
	public static void initialize () throws HibernateException {
		initialize((String) null);
	}
	
	/**
	 * Configure the session factory by reading hibernate config file
	 * @param configFileName the name of the configuration file
	 */
	public static void initialize (String configFileName) throws HibernateException {
		if (null == configFileName && sessionFactoryMap.size() > 0) return;
		else if (null != sessionFactoryMap.get(configFileName)) return;
		else {
			cfg = new Configuration();
			if (null == configFileName)
				cfg.configure();
			else
				cfg.configure(configFileName);
			setSessionFactory(configFileName, cfg.buildSessionFactory());
		}
	}
	
	public static Configuration getConfiguration() {
	    return cfg;
	}

	/**
	 * Set the session factory
	 */
	protected static void setSessionFactory (SessionFactory sessionFactory) {
		setSessionFactory((String) null, sessionFactory);
	}

	/**
	 * Set the session factory
	 */
	protected static void setSessionFactory (String configFileName, SessionFactory sessionFactory) {
		sessionFactoryMap.put(configFileName, sessionFactory);
	}

	/**
	 * Return the SessionFactory that is to be used by these DAOs.  Change this
	 * and implement your own strategy if you, for example, want to pull the SessionFactory
	 * from the JNDI tree.
	 */
	protected SessionFactory getSessionFactory() throws HibernateException {
		return getSessionFactory (getConfigurationFileName());
	}

	private static SessionFactory getSessionFactory(String configFile) throws HibernateException {
		if (sessionFactoryMap.size() == 1) return (SessionFactory) sessionFactoryMap.values().toArray()[0];
		else {
    		SessionFactory sessionFactory = (SessionFactory) sessionFactoryMap.get(configFile);
    		if (null == sessionFactory)
    			if (null == configFile)
    				throw new RuntimeException("The session factory has not been initialized.");
    			else
    				throw new RuntimeException("The session factory for '" + configFile + "' has not been initialized.");
    		else
    			return sessionFactory;
		}
	}

	/**
	 * Return a new Session object that must be closed when the work has been completed.
	 * @return the active Session
	 */
	protected Session getSession() throws HibernateException {
		return createSession();
	}

	/**
	 * Return a new Session object that must be closed when the work has been completed.
	 * @return the active Session
	 */
	public static Session createSession() throws HibernateException {
		return createSession(null);
	}

	/**
	 * Return a new Session object that must be closed when the work has been completed.
	 * @param configFile the config file must match the meta attribute "config-file" in the hibernate mapping file
	 * @return the active Session
	 */
	public static Session createSession(String configFile) throws HibernateException {
		java.util.Stack sessionStack = (java.util.Stack) threadedSessions.get();
		Session session = null;
		if (null == sessionStack) {
			sessionStack = new java.util.Stack();
			threadedSessions.set(sessionStack);
		}
		if (sessionStack.size() > 0) {
			Object[] arr = (Object[]) sessionStack.peek();
			String cf = (String) arr[0];
			if (null == cf) {
				session = (Session) arr[1];
			}
			else if (null != cf && null != configFile) {
				if (cf.equals(configFile)) session = (Session) arr[1];
			}
			if (null == session) {
				session = getSessionFactory(configFile).openSession();
				arr = new Object[2];
				arr[0] = configFile;
				arr[1] = session;
				sessionStack.push(arr);
			}
		}
		else {
			session = getSessionFactory(configFile).openSession();
			Object[] arr = new Object[2];
			arr = new Object[2];
			arr[0] = configFile;
			arr[1] = session;
			sessionStack.push(arr);
		}
		return session;
	}
	
	/**
	 * Return the name of the configuration file to be used with this DAO or null if default
	 */
	public String getConfigurationFileName () {
		return null;
	}

	/**
	 * Return the specific Object class that will be used for class-specific
	 * implementation of this DAO.
	 * @return the reference Class
	 */
	protected abstract Class getReferenceClass();

	/**
	 * Close the session
	 */
	public void closeSession () throws HibernateException {
		java.util.Stack sessionStack = (java.util.Stack) threadedSessions.get();
		if (null != sessionStack) {
			Object[] arr = (Object[]) sessionStack.peek();
			String cf = (String) arr[0];
			if (null == cf) {
				Session session = (Session) arr[1];
				session.close();
				sessionStack.pop();
			}
			else {
				String configurationFile = getConfigurationFileName();
				if (null != configurationFile && configurationFile.equals(cf)) {
					Session session = (Session) arr[1];
					session.close();
					sessionStack.pop();
				}
			}
		}
	}

	/**
	 * Begin the transaction related to the session
	 */
	public Transaction beginTransaction(Session s) throws HibernateException {
		return s.beginTransaction();
	}

	/**
	 * Commit the given transaction
	 */
	public void commitTransaction(Transaction t) throws HibernateException {
		t.commit();
	}
P

Valeu obrigado pela dica.

Criado 7 de junho de 2005
Ultima resposta 9 de jun. de 2005
Respostas 11
Participantes 2