jsf JPA完整示例

  • 本文关键字:JPA jsf jpa jsf-2
  • 更新时间 :
  • 英文 :


我正在使用netbeans开发jsf应用程序,到目前为止,我已经设计了一个输入表单post.xhtml并从数据库生成实体类以及从实体类生成jpa控制器。我现在如何调用jsf页面的方法来将数据保存到表中?

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();
        }
    }
}

首先要确保关闭字段内标记。添加按钮的形式,将用于存储数据到数据库。你的控制器更像一个服务,而不是控制器,但要给它添加@Named和@ViewScoped注释。添加动作:

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

然后添加带有setter和getter的NewPostEntity字段。

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

提示:在应用程序中为dao、服务和控制器创建不同的层。我的解决方案只是为了让你看看它是有效的,它不应该出现在最终产品中。

最新更新