2014-03-27 2 views
1

Я разрабатываю приложение jsf с использованием netbeans asn. До сих пор я разработал форму ввода post.xhtml и сгенерированные классы сущностей из базы данных, а также контроллеры jpa из классов сущностей. Как я могу теперь вызвать методы на странице jsf для сохранения данных в таблицах?JSF JPA FULL EXAMPECT

JSF страница по-прежнему без каких-либо тегов

<?xml version='1.0' encoding='UTF-8' ?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" 
     xmlns:ui="http://xmlns.jcp.org/jsf/facelets" 
     xmlns:h="http://xmlns.jcp.org/jsf/html"> 

    <body> 

     <ui:composition template="./WEB-INF/template/newTemplate.xhtml" > 
      <ui:define name="content"> 
       <h:inputText value="#{newPostEntityJpaController.}"></h:inputText> 
      </ui:define> 
     </ui:composition> 

    </body> 
</html> 


entity class 

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package Entities; 

import java.io.Serializable; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 

/** 
* 
* @author Admin 
*/ 
@Entity 
public class NewPostEntity implements Serializable { 
    private static final long serialVersionUID = 1L; 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 
    // fields 

    private Number budget; 
    private String details; 


    // 

    public void setDetails(String details) { 
     this.details = details; 
    } 

    public String getDetails() { 
     return details; 
    } 

    public void setBudget(Number budget) { 
     this.budget = budget; 
    } 

    public Number getBudget() { 
     return budget; 
    } 

    public Long getId() { 
     return id; 
    } 

    public void setId(Long id) { 
     this.id = id; 
    } 

    @Override 
    public int hashCode() { 
     int hash = 0; 
     hash += (id != null ? id.hashCode() : 0); 
     return hash; 
    } 

    @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 NewPostEntity)) { 
      return false; 
     } 
     NewPostEntity other = (NewPostEntity) object; 
     if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { 
      return false; 
     } 
     return true; 
    } 

    @Override 
    public String toString() { 
     return "Entities.NewEntity[ id=" + id + " ]"; 
    } 

} 


controller 

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package Controllers; 

import Controllers.exceptions.NonexistentEntityException; 
import Controllers.exceptions.RollbackFailureException; 
import Entities.NewPostEntity; 
import java.io.Serializable; 
import java.util.List; 
import javax.persistence.EntityManager; 
import javax.persistence.EntityManagerFactory; 
import javax.persistence.Query; 
import javax.persistence.EntityNotFoundException; 
import javax.persistence.criteria.CriteriaQuery; 
import javax.persistence.criteria.Root; 
import javax.transaction.UserTransaction; 

/** 
* 
* @author Admin 
*/ 

public class NewPostEntityJpaController implements Serializable { 

    public NewPostEntityJpaController(UserTransaction utx, EntityManagerFactory emf) { 
     this.utx = utx; 
     this.emf = emf; 
    } 
    private UserTransaction utx = null; 
    private EntityManagerFactory emf = null; 

    public EntityManager getEntityManager() { 
     return emf.createEntityManager(); 
    } 

    public void create(NewPostEntity newPostEntity) throws RollbackFailureException, Exception { 
     EntityManager em = null; 
     try { 
      utx.begin(); 
      em = getEntityManager(); 
      em.persist(newPostEntity); 
      utx.commit(); 
     } catch (Exception ex) { 
      try { 
       utx.rollback(); 
      } catch (Exception re) { 
       throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); 
      } 
      throw ex; 
     } finally { 
      if (em != null) { 
       em.close(); 
      } 
     } 
    } 

    public void edit(NewPostEntity newPostEntity) throws NonexistentEntityException, RollbackFailureException, Exception { 
     EntityManager em = null; 
     try { 
      utx.begin(); 
      em = getEntityManager(); 
      newPostEntity = em.merge(newPostEntity); 
      utx.commit(); 
     } catch (Exception ex) { 
      try { 
       utx.rollback(); 
      } catch (Exception re) { 
       throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); 
      } 
      String msg = ex.getLocalizedMessage(); 
      if (msg == null || msg.length() == 0) { 
       Long id = newPostEntity.getId(); 
       if (findNewPostEntity(id) == null) { 
        throw new NonexistentEntityException("The newPostEntity with id " + id + " no longer exists."); 
       } 
      } 
      throw ex; 
     } finally { 
      if (em != null) { 
       em.close(); 
      } 
     } 
    } 

    public void destroy(Long id) throws NonexistentEntityException, RollbackFailureException, Exception { 
     EntityManager em = null; 
     try { 
      utx.begin(); 
      em = getEntityManager(); 
      NewPostEntity newPostEntity; 
      try { 
       newPostEntity = em.getReference(NewPostEntity.class, id); 
       newPostEntity.getId(); 
      } catch (EntityNotFoundException enfe) { 
       throw new NonexistentEntityException("The newPostEntity with id " + id + " no longer exists.", enfe); 
      } 
      em.remove(newPostEntity); 
      utx.commit(); 
     } catch (Exception ex) { 
      try { 
       utx.rollback(); 
      } catch (Exception re) { 
       throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); 
      } 
      throw ex; 
     } finally { 
      if (em != null) { 
       em.close(); 
      } 
     } 
    } 

    public List<NewPostEntity> findNewPostEntityEntities() { 
     return findNewPostEntityEntities(true, -1, -1); 
    } 

    public List<NewPostEntity> findNewPostEntityEntities(int maxResults, int firstResult) { 
     return findNewPostEntityEntities(false, maxResults, firstResult); 
    } 

    private List<NewPostEntity> findNewPostEntityEntities(boolean all, int maxResults, int firstResult) { 
     EntityManager em = getEntityManager(); 
     try { 
      CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); 
      cq.select(cq.from(NewPostEntity.class)); 
      Query q = em.createQuery(cq); 
      if (!all) { 
       q.setMaxResults(maxResults); 
       q.setFirstResult(firstResult); 
      } 
      return q.getResultList(); 
     } finally { 
      em.close(); 
     } 
    } 

    public NewPostEntity findNewPostEntity(Long id) { 
     EntityManager em = getEntityManager(); 
     try { 
      return em.find(NewPostEntity.class, id); 
     } finally { 
      em.close(); 
     } 
    } 

    public int getNewPostEntityCount() { 
     EntityManager em = getEntityManager(); 
     try { 
      CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); 
      Root<NewPostEntity> rt = cq.from(NewPostEntity.class); 
      cq.select(em.getCriteriaBuilder().count(rt)); 
      Query q = em.createQuery(cq); 
      return ((Long) q.getSingleResult()).intValue(); 
     } finally { 
      em.close(); 
     } 
    } 

} 
+0

Основная таблица DataTable Lazy Загрузка с разбивкой по страницам, фильтрация и сортировка с использованием критериев JPA, @ViewScoped - http://leonotepad.blogspot.com.br/2014/01/primefaces-datatable-lazy-loading-with.html – Leo

+0

будет проверять и вернуться –

ответ

0

Прежде всего убедитесь, что закрыть поле внутри тега. Добавить кнопку для формирования, которая будет использоваться для хранения данных в БД. Ваш контроллер больше похож на службу, чем контроллер, но добавляет к ней аннотации @Named и опционально @ViewScoped. Добавьте туда действие:

public void savePost(){ 
if (newPostEntity != null) 
create(newPostEntity); 
} 

Затем добавьте поле NewPostEntity newPostEntity с установщиком и геттером.

<h:form> 
    <h:inputText value="#{newPostEntityJpaController.newPostEntity.details}"></h:inputText> 
    <h:commandButton action="#{newPostEntityJpaController.saveMessage}"> 
</h:form> 

СОВЕТ. Создайте в своем приложении другой слой для dao, sevice и controller. Мое решение просто для того, чтобы показать, что оно работает, и оно не должно быть в конечном продукте.

Смежные вопросы