Hibernate e Struts

8 respostas
tads

Olá pessoal,

Novamente sobre hibernate.
Estou tentando fazer uma query simples no hibernate, através do
método createQuery. Estou usando assim:

String query = "";

query = "select user.idUser, user.name"
  + " from User user";

Query q = session.createQuery(query);

ArrayList list = (ArrayList) q.list();

Neste caso, ele me retorna uma lista de Object[2], pois na
query tem apenas 2 colunas, que são as que eu quero.

Como eu faria então no Struts?
Tenho q criar um Bean apenas com estes atributos??

No Hibernate Reference somente mostra q retorna um List
de objetos.

Se alguém puder me ajudar…

Obrigado,

Tadeu

8 Respostas

ricardolecheta

isto é realmente chato!

vc poderia tentar assim:

select new User(user.idUser, user.name) from User as user

isto retornaria uma List de User, mas na classe User precisa ter um construtor que recebe estes dois campos.

public User(Integer idUser,String name) {}

caso queira percorrer a lista de Object[2], precisa fazer um iterate dentro de outro;

<logic:iterate id="user" name="users" scope='request'>
        <logic:iterate id="currentObj" name="user">
                       <bean:write name="currentObj" />
        </logic:iterate>
</logic:iterate>

o 1º iterate percorre a Lista, e o 2º percorre o Object[2] :smiley:

tads

E ai Ricardo, blz??

Legal o exemplo q vc me passou, mas este seria apenas
criar construtor de uma classe e iniciar apenas alguns atributos de
apenas uma classe.
E se eu for usar diversas colunas de diversas tabelas. Por exemplo,
eu crio uma query com joins, e com cálculos, estas coisas.

Eu não tenho um bean criado para isso.

Como eu procederia neste caso???

Valew pela ajuda…

Abraço,

ricardolecheta

neste caso do join tb vai retornar uma lista de Object[] para cada campo que vc especificou…

então teria que fazer aquele “iterate” que mostrei… é o único jeito que arranjei de fazer isto…

tads

E ai, tudo bom?

Bom, uma outra solução (não sei se a melhor) pode ser criar um outro bean que contenha atributos que correspondem a colunas de diferentes
tabelas.

Muito obrigado pela ajuda,

abraço

ricardolecheta

e aquele “HibernatePlugIn” para o Struts funcionou?

tads

Então carinha, funcionou… aos trancos e barrancos… tive que
mudar umas coisas pra poder funcionar, pois
no Hibernate Reference diz pra se jogar o hibernate.cfg.xml
no classpath.
quando eu NAO estava usando o HibernatePlugIn, tava funcionando.
Usando esta classe não funciona, pois não acha o cfg.xml
Então, eu tive que colocá-lo na pasta onde está os jsps, onde contém o WEB-INF por exemplo. Não dentro do WEB-INF, mas no mesmo
nível deste. (Vixe, acho q não fui muito claro).

Se alguém quiser a classe eu posso passar aki,
mas eu mudei os esquemas de log, pois eu to usando o log4j.

falow

ricardolecheta

legal!

pode mandar para mim a classe então, e o seu hibernate.cfg.xml ?

valeu tads!

um abraço

tads

To deixando disponivel aki:

HibernatePlugIn.java

package pacoce;

import java.io.File;
//import java.net.URL;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;


/**
 * Implements the PlugIn interface to configure the Hibernate data
 * persistence library.  A configured
 * net.sf.hibernate.SessionFactory is stored in the
 * ServletContext of the web application unless the property
 * storedInServletContext is set to false.
 * 
 * <plugin
 * class="net.sf.hibernate.plugins.struts.HibernatePlugIn">
 * <set-property name="configFilePath&quot"
 * value="path-to-config-file"/> <set-property
 * name="storedInServletContext&quot"
 * value="true-or-false"/> </plugin>
 *
* @author  <a href="mailto:[email removido]">Bradley M. Handy</a>
 * @version 07/10/2003
 */

public class HibernatePlugIn implements PlugIn
{
    /**
     * the key under which the SessionFactory instance is stored
     * in the ServletContext.
     */
    public static final String SESSION_FACTORY_KEY = SessionFactory.class.getName();

	/** Object to access log4j */
	static Logger log = Logger.getLogger(HibernatePlugIn.class);
    
    /**
     * indicates whether the SessionFactory instance will be
     * stored in the ServletContext, or not.
     */
    private boolean storedInServletContext = true;

    /**
     * the path to the xml configuration file.  the path should start with a
     * '/' character and be relative to the root of the class path. (DEFAULT:
     * "/hibernate.cfg.xml")
     */
    private String configFilePath = "/hibernate.cfg.xml";

    /** servlet */
    private ActionServlet servlet = null;

    /** Module of configuration */
    private ModuleConfig config = null;

    /** Session Factory */
    private SessionFactory factory = null;

    /**
     * Destroys the SessionFactory instance.
     */
    public void destroy()
    {
        this.servlet = null;
        this.config = null;

        try
        {
            log.debug("Destroying SessionFactory...");

            factory.close();

            log.debug("SessionFactory destroyed...");
        }
        catch (Exception e)
        {
            log.error("Unable to destroy SessionFactory...(exception ignored)", e);
        }
    }

    /**
     * Initializes the SessionFactory.
     *
     * @param servlet the ActionServlet instance under which the
     *        plugin will run.
     * @param config the ModuleConfig for the module under which
     *        the plugin will run.
     *
     * @throws ServletException Exception
     */
    public void init(ActionServlet servlet, ModuleConfig config)
        throws ServletException
    {
        this.servlet = servlet;
        this.config = config;

        initHibernate();
    }

    /**
     * Initializes Hibernate with the config file found at
     * configFilePath.
     *
     * @throws ServletException Exception
     */
    private void initHibernate() throws ServletException
    {
        Configuration configuration = null;
        ServletContext context = null;

        try
        {
            context = servlet.getServletContext();

            if (log.isDebugEnabled())
            {
                log.debug("Initializing Hibernate from " + this.configFilePath + "...");
            }
            
            String path = context.getRealPath(this.configFilePath);
            File file = new File(path);

            configuration = (new Configuration()).configure(file);
            
            this.factory = configuration.buildSessionFactory();

            if (this.storedInServletContext)
            {
                log.debug("Storing SessionFactory in ServletContext...");
                context.setAttribute(SESSION_FACTORY_KEY, this.factory);
            }
        }
        catch (Throwable t)
        {
            log.error("Exception while initializing Hibernate.");
            log.error("Rethrowing exception...", t);

            throw (new ServletException(t));
        }
    }

    /**
     * Setter for property configFilePath.
     *
     * @param configFilePath New value of property configFilePath.
     *
     * @throws IllegalArgumentException Exception
     */
    public void setConfigFilePath(String configFilePath)
    {
        if ((configFilePath == null) || (configFilePath.trim().length() == 0))
        {
            throw new IllegalArgumentException(
                "configFilePath cannot be blank or null.");
        }

        if (log.isDebugEnabled())
        {
            log.debug("Setting 'configFilePath' to '" + configFilePath
                + "'...");
        }

        this.configFilePath = configFilePath;
    }

    /**
     * Setter for property storedInServletContext.
     *
     * @param storedInServletContext New value of property
     *        storedInServletContext.
     */
    public void setStoredInServletContext(String storedInServletContext)
    {
        if ((storedInServletContext == null)
                    || (storedInServletContext.trim().length() == 0))
        {
            storedInServletContext = "false";
        }

        if (log.isDebugEnabled())
        {
            log.debug("Setting 'storedInServletContext' to '"
                + storedInServletContext + "'...");
        }

        this.storedInServletContext = new Boolean(storedInServletContext)
            .booleanValue();
    }
}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 2.0//EN"

 "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

<hibernate-configuration>

    <!-- a SessionFactory instance listed as /jndi/name -->
    <session-factory>

        <!-- properties -->
	
		<property name="dialect">net.sf.hibernate.dialect.OracleDialect</property>
		<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
		<property name="connection.url">jdbc:oracle:thin:@oraserv:1521:database</property>
		<property name="connection.username">user</property>
		<property name="connection.password">senha</property>

		<property name="connection.pool_size">1</property>
		<property name="statement_cache.size">25</property>

        <property name="show_sql">true</property>
        <property name="use_outer_join">true</property>

		<property name="jdbc.batch_size">0</property>
		<property name="jdbc.use_streams_for_binary">true</property>

		<property name="cglib.use_reflection_optimizer">false</property>

        <!-- mapping files-->
        <mapping resource="br/com/hst/dao/register/Department.hbm.xml"/>
        <mapping resource="br/com/hst/dao/register/Template.hbm.xml"/>

		<mapping resource="br/com/hst/dao/register/User.hbm.xml"/>
		<mapping resource="br/com/hst/dao/register/Product.hbm.xml"/>
		<mapping resource="br/com/hst/dao/register/Action.hbm.xml"/>		

    </session-factory>

</hibernate-configuration>
Criado 8 de outubro de 2003
Ultima resposta 8 de out. de 2003
Respostas 8
Participantes 2