4 Replies Latest reply on Oct 20, 2009 4:12 PM by jeanluc

    Working with JBoss using seam architecture layers?

    ibmoreno

      Working with JBoss using seam architecture layers, DAO, Business. Below my classes.



      My class DAO


      @Name("userDAO")
      public class UserDAO<E, PK extends Serializable> {
      
           @In
           private Session hibernateSession;
      
           /**
            * Classe passada como Generico para manipulacao.
            * 
            */
           private Class<E> entityClass;
      
           /**
            * Construtor AbstractDAO
            * 
            * @param clazz
            */
           public UserDAO(Class<E> clazz) {
                this.entityClass = clazz;
           }
      
           /**
            * Metodo para recuperar todos os objetos persistido no Banco de Dados.
            * 
            * @return List<E>, lista de Objetos.
            * 
            * @throws SasException
            */
           @SuppressWarnings("unchecked")
           public List<E> findAll() throws SasException {
      
                try {
      
                     Criteria criteria = getHibernateSession().getSessionFactory()
                               .getCurrentSession().createCriteria(entityClass);
                     criteria.addOrder(Order.asc("nome"));
                     return criteria.list();
      
                } catch (HibernateException hibernateException) {
                     throw new SasException(String
                               .format("Não foi possível carregar a lista de objetos."),
                               hibernateException);
                }
      
           }
      
           /**
            * Metodo para retornar Objeto persistido no Banco de Dados pelo Id
            * informado no parametro.
            * 
            * @param id
            *            , valor do Id do objeto persistido.
            * 
            * @return Objeto persistido.
            * 
            * @throws SasException
            */
           @SuppressWarnings("unchecked")
           public E findById(PK id) throws SasException {
      
                try {
      
                     return (E) getHibernateSession().get(entityClass, id);
      
                } catch (HibernateException hibernateException) {
                     throw new SasException(
                               String
                                         .format(
                                                   "Não foi possível recuperar o objeto identificado por '%d'.",
                                                   id), hibernateException);
                }
      
           }
      
           /**
            * Metodo para recuperar todos os objetos persistido no Banco de Dados, pelo
            * valor da propriedade do Objeto informado.
            * 
            * @param propertyName
            *            , nome da propriedade a ser usado como criteria de consulta.
            * @param propertyValue
            *            , valor da propriedade informada.
            * 
            * @return List<E>, lista de Objetos.
            * 
            * @throws SasException
            */
           @SuppressWarnings("unchecked")
           public List<E> findByProperty(String propertyName, Object propertyValue)
                     throws SasException {
      
                try {
      
                     Criteria criteria = getHibernateSession().getSessionFactory()
                               .getCurrentSession().createCriteria(entityClass);
      
                     criteria.add(Restrictions.ilike(propertyName, propertyValue));
                     criteria.addOrder(Order.asc(propertyName));
                     return criteria.list();
      
                } catch (HibernateException hibernateException) {
                     throw new SasException(
                               String
                                         .format("Não foi possível carregar a lista de objetos para o nome: "
                                                   + propertyValue + "."), hibernateException);
                }
           }
      
           /**
            * Metodo para remover objeto persistido no Banco de Dados.
            * 
            * @param entityClass
            *            , Objeto Entity persistido.
            * 
            * @throws SasException
            */
           public void remove(E entityClass) throws SasException {
      
                try {
      
                     getHibernateSession().delete(entityClass);
      
                } catch (HibernateException hibernateException) {
                     throw new SasException("Não foi possível remover o objeto.");
                }
           }
      
           /**
            * Metodo para persistir o objeto no Banco de Dados.
            * 
            * @param entityClass
            *            , Objeto Entity a ser persistido.
            * 
            * @throws SasException
            */
           public void save(E entityClass) throws SasException {
      
                try {
      
                     getHibernateSession().saveOrUpdate(entityClass);
      
                } catch (HibernateException hibernateException) {
                     throw new SasException("Não foi possível salvar o objeto");
                }
           }
      
           /**
            * Metodo para recuterar a Sessao do Banco de Dados do Hibernate.
            * 
            * @return Session.
            */
           public Session getHibernateSession() {
                return hibernateSession;
           }
           
           public void setHibernateSession(Session hibernateSession) {
                this.hibernateSession = hibernateSession;
           }     
      
      }
      
      



      My class BO


      @Name("userBO")
      public class UserBO {
      
           private UserDAO<Estado, String> userDAOEstado;
      
           @Factory(value = "userDAOEstado", autoCreate = true)
           public void initUserDAOEstado() {
                userDAOEstado = new UserDAO<Estado, String>(Estado.class);
           }
      
           public void saveEstado(Estado estado) {
                userDAOEstado.save(estado);
           }
      
      }
      



      My class Action


      @Name("acionBeanUser")
      @Scope(ScopeType.EVENT)
      public class ActionBeanUser {
      
           @In(value = "userBO", create = true)
           private UserBO userBO;
      
           public void save() {
      
                Estado estado = new Estado();
                estado.setEstadoId("MT");
                estado.setNome("MATO GROSSO");
      
                userBO.saveEstado(estado);
      
           }
      
      }
      



      My components.xml


      <?xml version="1.0" encoding="UTF-8"?>
      <components xmlns="http://jboss.com/products/seam/components"
           xmlns:core="http://jboss.com/products/seam/core" xmlns:persistence="http://jboss.com/products/seam/persistence"
           xmlns:security="http://jboss.com/products/seam/security" xmlns:drools="http://jboss.com/products/seam/drools"
           xmlns:web="http://jboss.com/products/seam/web" xmlns:mail="http://jboss.com/products/seam/mail"
           xmlns:transaction="http://jboss.com/products/seam/transaction"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ui="http://jboss.com/products/seam/ui"
           xsi:schemaLocation="http://jboss.com/products/seam/core http://jboss.com/products/seam/core-2.1.xsd
               http://jboss.com/products/seam/persistence http://jboss.com/products/seam/persistence-2.1.xsd
              http://jboss.com/products/seam/security http://jboss.com/products/seam/security-2.1.xsd
              http://jboss.com/products/seam/ui http://jboss.com/products/seam/ui-2.1.xsd
              http://jboss.com/products/seam/transaction http://jboss.com/products/seam/transaction-2.1.xsd
              http://jboss.com/products/seam/components http://jboss.com/products/seam/components-2.1.xsd
              http://jboss.com/products/seam/mail http://jboss.com/products/seam/mail-2.1.xsd">
      
           <core:manager conversation-timeout="120000"
                concurrent-request-timeout="500" conversation-id-parameter="cid" />
      
           <persistence:hibernate-session-factory
                name="hibernateSessionFactory" />
      
           <persistence:managed-hibernate-session
                name="hibernateSession" session-factory="#{hibernateSessionFactory}"
                auto-create="true" />
      
           <transaction:hibernate-transaction
                session="#{hibernateSession}" />
      
      </components>
      



      The problem is that the DAO class is not injecting HibernateSession that is in context, I believe it is because it is using the @Factory instead of @In more using @ In in a class of features. How to do?


      thank you


      Ivan

        • 1. Re: Working with JBoss using seam architecture layers?
          kapitanpetko

          To use Seam injection, etc, you need to instantiate your components using Component.getInstance() or let Seam do it for you with @In(create=true) or @Autocreate. But since you don't have a default constructor and Component know nothing about your generic
          parameters, this won't work as is. The easiest thing would be to get the Session in your DAO using getInstance. Something like:


          public E findById(PK id) throws SasException {
            Session  session = Component.getInstance("hibernateSession");
          
            return (E) session.get(entityClass, id);
          }
          



          And you don't really need the factory in your BO, unless you want the DAO to be accessible to your UI.


          Before you write all that code though, ask yourself: do you really need all this just to say: session.saveOrUpdate()?
          Just inject the session in ActionBeanUser and save yourself some trouble. Unless you are required to have layers and
          there is no way around it.


          HTH

          • 2. Re: Working with JBoss using seam architecture layers?
            ibmoreno

            Thank you, I will try to simplify. I'm beginning to use JBoss Seam and recently used to separate, I see that JBoss Seam is changing this or not?

            • 3. Re: Working with JBoss using seam architecture layers?
              asookazian

              Layering is optional in Seam (unlike other frameworks like Struts with Spring, etc.)


              You should consider adding a DAO, service, etc. layer if your app has a lot of business logic as well as db logic.  If it's a small CRUD app with minimal biz logic, why make it unnecessarily complicated?

              • 4. Re: Working with JBoss using seam architecture layers?
                jeanluc

                There's also a lot of overhead with the added exception handling. Why wrap all the exceptions into an SasException? If SasException is checked, it has an impact on all the callers). This is a general design issue, though, and not related to whether Seam is used or not.