使用NetBeans+PrimeFaces实现一个增删改查

第一步:我们现在pom.xml中添加:

        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>6.0</version>   
        </dependency>

第二步:添加实体类,数据库的表我们自己建一张就可以

        package com.lys.pojo;

        import java.io.Serializable;
        import java.util.Date;
        import javax.persistence.Basic;
        import javax.persistence.Column;
        import javax.persistence.Entity;
        import javax.persistence.Id;
        import javax.persistence.NamedQueries;
        import javax.persistence.NamedQuery;
        import javax.persistence.Table;
        import javax.persistence.Temporal;
        import javax.persistence.TemporalType;
        import javax.validation.constraints.NotNull;
        import javax.validation.constraints.Size;
        import javax.xml.bind.annotation.XmlRootElement;


        @Entity
        @Table(name = "job")
        @XmlRootElement
        @NamedQueries({
            @NamedQuery(name = "Job.findAll", query = "SELECT j FROM Job j")
        })
        public class Job implements Serializable {

            private static final long serialVersionUID = 1L;
            @Size(max = 8)
            @Column(name = "jname")
            private String jname;
            @Id
            @Basic(optional = false)
            @NotNull
            @Column(name = "jid")
            private Integer jid;
            @Column(name = "jage")
            private Integer jage;
            @Column(name = "jtime")
            @Temporal(TemporalType.DATE)
            private Date jtime;
            @Size(max = 4)
            @Column(name = "jsex")
            private String jsex;

            public Job() {
            }

            public Job(Integer jid) {
                this.jid = jid;
            }

            public String getJname() {
                return jname;
            }

            public void setJname(String jname) {
                this.jname = jname;
            }

            public Integer getJid() {
                return jid;
            }

            public void setJid(Integer jid) {
                this.jid = jid;
            }

            public Integer getJage() {
                return jage;
            }

            public void setJage(Integer jage) {
                this.jage = jage;
            }

            public Date getJtime() {
                return jtime;
            }

            public void setJtime(Date jtime) {
                this.jtime = jtime;
            }

            public String getJsex() {
                return jsex;
            }

            public void setJsex(String jsex) {
                this.jsex = jsex;
            }

            @Override
            public int hashCode() {
                int hash = 0;
                hash += (jid != null ? jid.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 Job)) {
                    return false;
                }
                Job other = (Job) object;
                if ((this.jid == null && other.jid != null) || (this.jid != null && !this.jid.equals(other.jid))) {
                    return false;
                }
                return true;
            }

            @Override
            public String toString() {
                return "com.lys.pojo.Job[ jid=" + jid + " ]";
            }

        }

第三步:编写service层,就是通过实体类生成REST风格的web服务,代码如下

AbstractFacade类:


package com.lys.service;

import java.util.List;
import javax.persistence.EntityManager;


public abstract class AbstractFacade<T> {

    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public void edit(T entity) {
        getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0] + 1);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

}

JobFacadeREST类:


package com.lys.service;

import com.lys.pojo.Job;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;


@Stateless
@Path("com.lys.pojo.job")
public class JobFacadeREST extends AbstractFacade<Job> {

    @PersistenceContext(unitName = "com.mycompany_demo_03_war_1.0-SNAPSHOTPU")
    private EntityManager em;

    public JobFacadeREST() {
        super(Job.class);
    }

    @POST
    @Override
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public void create(Job entity) {
        super.create(entity);
    }

    @PUT
    @Path("{id}")
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public void edit(@PathParam("id") Integer id, Job entity) {
        super.edit(entity);
    }

    @DELETE
    @Path("{id}")
    public void remove(@PathParam("id") Integer id) {
        super.remove(super.find(id));
    }

    @GET
    @Path("{id}")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public Job find(@PathParam("id") Integer id) {
        return super.find(id);
    }

    @GET
    @Override
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public List<Job> findAll() {

        return super.findAll();
    }

    @GET
    @Path("{from}/{to}")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public List<Job> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
        return super.findRange(new int[]{from, to});
    }

    @GET
    @Path("count")
    @Produces(MediaType.TEXT_PLAIN)
    public String countREST() {
        return String.valueOf(super.count());
    }

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public int creatJob(Job job) {
        try {

            if ((Long) em.createQuery("select count(j) from Job j where j.jname=:name").setParameter("name", job.getJname()).getSingleResult() > 0) {
                return 1;
            }
            Object maxno = em.createQuery("select max(j.jid) from Job j").getSingleResult();
            int max = 0;
            if (maxno != null) {
                max = Integer.parseInt(maxno.toString());
            }
            job.setJid(max + 1);
            super.create(job);

        } catch (Exception e) {
            e.printStackTrace();
            return 2;
        }

        return 3;

    }

    public int editJob(Job job) {
        try {
            if ((long) em.createQuery("select count(j) from Job j where j.jname=:name and j.jid!=:jobno").setParameter("name", job.getJname())
                    .setParameter("jobno", job.getJid()).getSingleResult() > 0) {
                return 1;
            }

            super.edit(job);
        } catch (Exception e) {
            e.printStackTrace();
            return 2;
        }
        return 3;
    }

    public int delJob(Job job) {
        int n = em.createQuery("delete from Job where jid=:jid").setParameter("jid", job.getJid()).executeUpdate();
        return n;

    }

}

第四步:编写action,代码如下:

package com.lys.action;

import com.lys.pojo.Job;
import com.lys.service.JobFacadeREST;
import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.context.RequestContext;

@Named("job")
@ViewScoped
public class JobAction implements Serializable {

    @Inject
    private JobFacadeREST jobejb;

    private List<Job> datalist;
    private Job job;
    private String title;
    private int mode;
    private Map<Integer, String> jobName;

    @PostConstruct
    private void init() {
        jobName = new HashMap();
        gofind();
    }

    private void gofind() {
        List<Job> list = jobejb.findAll();
        if (list == null) {
            datalist = new ArrayList();
        } else {
            datalist = list;
        }
        findjobName();

    }

    private void findjobName() {
        jobName.clear();
        if (!datalist.isEmpty()) {
            for (Job j : datalist) {
                jobName.put(j.getJid(), j.getJname());
            }
        }
    }

    public void addJob() {
        title = "添加职位";
        mode = 1;
        job = new Job();
        RequestContext.getCurrentInstance().execute("PF('dig').show()");

    }

    public void edjJob() {
        if (job == null || job.getJname() == null) {
            message("提示", "请选择要编辑的对象!");
            return;
        }
        title = "编辑职位";
        mode = 2;

        RequestContext.getCurrentInstance().execute("PF('dig').show()");

    }

    public void saveJob() throws ParseException {

        if (mode == 1) {
            job.setJtime(new Date());
            int res = jobejb.creatJob(job);
            if (res == 1) {
                message("保存失败", "该名称已经被使用");
                return;
            }
            if (res == 2) {
                message("提示", "保存失败");
                return;
            }
            message("提示", "保存成功!");
            gofind();
            RequestContext.getCurrentInstance().execute("PF('dig').hide()");

        } else {
            int res = jobejb.editJob(job);
            if (res == 1) {
                message("保存失败", "该名称已经被使用");
                return;
            }
            if (res == 2) {
                message("提示", "保存失败");
                return;
            }
            message("提示", "修改成功!");
            gofind();
            RequestContext.getCurrentInstance().execute("PF('dig').hide()");

        }

    }

    public void selected() {
        String name = "";
        if (job != null) {
            name = job.getJname();
        }
        System.out.println("job name " + name);
    }

    public void delJob() {
        if (job == null || job.getJname() == null) {
            message("提示", "请选择要删除的对象!");
            return;
        }
        RequestContext.getCurrentInstance().execute("PF('dig2').show()");
    }

    public void sureDel() {
        int res = jobejb.delJob(job);
        if (res == 1) {
            message("提示", "删除成功!");
            gofind();
        }

    }

    private void message(String msg, String detail) {
        FacesContext.getCurrentInstance().addMessage("msg", new FacesMessage(FacesMessage.SEVERITY_INFO, msg, detail));
    }

    public List<Job> getDatalist() {
        return datalist;
    }

    public void setDatalist(List<Job> datalist) {
        this.datalist = datalist;
    }

    public Job getJob() {
        return job;
    }

    public void setJob(Job job) {
        this.job = job;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Map<Integer, String> getJobName() {
        return jobName;
    }

    public void setJobName(Map<Integer, String> jobName) {
        this.jobName = jobName;
    }
}

第五步:编写job.xhtml,代码如下:

<html  xmlns="http://www.w3.org/1999/xhtml"
       xmlns:f="http://xmlns.jcp.org/jsf/core"
       xmlns:h="http://xmlns.jcp.org/jsf/html"
       xmlns:c="http://java.sun.com/jsp/jstl/core"
       xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
       xmlns:p="http://primefaces.org/ui">

    <h:head>
        Job
    </h:head>

    <h:body>
        <div  style="padding-left: 50px;padding-right: 50px;">
            <h:panelGrid columns="4" width="80%" id="save">
                <h3>这是一个小demo</h3>
            </h:panelGrid>
        </div>  
        <h:form id="fm">
            <div id="noback"  style="padding-left: 30px;padding-right: 30px;padding-top: 50px;padding-bottom: 50px">

                <p:panel>
                    <f:facet name="header">
                        <h:panelGroup style="float: right" >
                            <p:commandButton icon="fa fa-plus" actionListener="#{job.addJob()}" process="@this " update="fm" />
                            <p:commandButton icon="fa fa-edit" actionListener="#{job.edjJob()}" process="@this" update="fm" />
                            <p:commandButton icon="fa fa-close"  actionListener="#{job.delJob()}" process="@this" update="fm" />
                        </h:panelGroup>
                    </f:facet>

                    <p:dataTable value="#{job.datalist}" var="dt" emptyMessage="还没有职位!" selectionMode="single" selection="#{job.job}" rowKey="#{dt.jid}" 
                                 rows="10" paginator="true" paginatorPosition="bottom" styleClass="TexAlCenter"
                                 paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
                                 rowsPerPageTemplate="5,10,15" >          
                        <p:ajax event="rowSelect" listener="#{job.selected()}" />

                        <p:column headerText="名称" width="30%">
                            <h:outputText value="#{dt.jname}" style="display: flex; justify-content: center;"/>

                        </p:column>
                        <p:column headerText="时间" width="30%">
                            <h:outputText value="#{dt.jtime}" style="display: flex; justify-content: center;"/>
                        </p:column>
                        <p:column headerText="年龄" width="40%">
                            <h:outputText value="#{dt.jage}" style="display: flex; justify-content: center;"/>
                        </p:column>
                        <p:column headerText="性别" width="40%">
                            <h:outputText value="#{dt.jsex}" style="display: flex; justify-content: center;"/>
                        </p:column>

                    </p:dataTable>
                </p:panel>
            </div>

            <p:dialog closable="true" header="#{job.title}" id="dig" widgetVar="dig" modal="true" resizable="false" >
                <h:panelGrid columns="2" cellpadding="10px" cellspacing="20px" columnClasses="Wid40,Wid60" width="500px">
                    <h:outputText value="姓名:"/>
                    <p:inputText value="#{job.job.jname}" style="width: 400px" required="true" requiredMessage="姓名不能为空"/>
                    <h:outputText value="年龄:"/>
                    <p:inputText value="#{job.job.jage}" style="width: 400px;font-size: 20px" required="true" requiredMessage="年龄不能为空!"/>
                    <h:outputText value="性别:"/>
                    <p:inputText value="#{job.job.jsex}" style="width: 400px"/>

                </h:panelGrid>
                <div style="width: 100%;height: 30px;">
                    <div style="float: right">
                        <p:commandButton value="取消" partialSubmit="false"  onclick="PF('dig').hide()"/>
                        <p:spacer width="10px"/>
                        <p:commandButton value="保存" process="@this dig" update="fm" actionListener="#{job.saveJob()}"/>
                        <p:spacer width="30px"/>
                    </div>
                </div>
                <div style="height: 30px;width: 100%;"/>
            </p:dialog>

            <p:dialog width="350px" height="200px" header="对话框" widgetVar="dig2" id="dig2" closable="true" modal="true" resizable="false">
                <br/>
                <h:outputText value="您确定要删除#{job.job.jname}吗?" style="font-size: large; color: crimson"/>
                <br/><br/><br/><br/><br/><br/>
                <p:separator/>
                <p:spacer width="120px" height="10px"/>
                <p:commandButton value="取消" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close" onclick="PF('dig2').hide()"/>
                <p:spacer width="20px" height="10px"/>
                <p:commandButton value="确定"  actionListener="#{job.sureDel()}" styleClass="ui-confirmdialog-yes" icon="ui-icon-check" oncomplete="PF('dig2').hide()" update="fm" process="@this"/>
            </p:dialog>
            <p:growl id="msg" showDetail="true" life="2000"/>
        </h:form>

        <p:growl id="msg" showDetail="true" life="2000"/>
    </h:body>


</html>

这样就完成了,需要注意的电放就是,web.xml需要把<welcome-file>job.xhtml</welcome-file>这个地方改一下,要不然每次进去都要手动输入一个地址,数据库的配置也要写好.

<resources>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="mysql_job_rootPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="serverName" value="localhost"/>
        <property name="portNumber" value="3306"/>
        <property name="databaseName" value="job"/>
        <property name="User" value="root"/>
        <property name="Password" value="root"/>
        <property name="URL" value="jdbc:mysql://localhost:3306/job?zeroDateTimeBehavior=convertToNull"/>
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    </jdbc-connection-pool>
    <jdbc-resource enabled="true" jndi-name="java:app/job" object-type="user" pool-name="mysql_job_rootPool"/>
</resources>

第一次写,有什么不足想大家能理解并且指出错误,我们一起,奋斗不止 梦想不断!!!

猜你喜欢

转载自blog.csdn.net/qq_42382404/article/details/81458411
今日推荐