如何在Primefaces中实现保存按钮

时间:2014-05-18 11:44:02

标签: java jsf primefaces

我在primefaces中写了一个表单,我想在我的数据库中显示和更改我的数据。现在我想做,用户可以更改前端的数据,如果他重新加载页面,可以撤消它。在此页面上应该是一个保存按钮,只有按下此按钮,数据才会保存在数据库中。

目前我遇到了问题,如果我运行onSave方法,我看不到上一个函数onEdit的变量。所以我只将错误的数据写入数据库。

EditObject.java:

@ManagedBean
public class EditObjects implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private List<Objects> myObjects;
    private Source[] mySources;

    public EditObjects() {
        ObjectsDAO odao = new ObjectsDAO();
        myObjects = odao.getAllObjects();
        SourceDAO sdao = new SourceDAO();
        mySources = sdao.getSourceList();
    }

    public Source[] getSourceList() {
        return mySources;
    }

    public List<Objects> getMyObjects() {
        return myObjects;
    }

    public void setMyObjects(List<Objects> myObjects) {
        this.myObjects = myObjects;
    }

    public Source[] getMySources() {
        return mySources;
    }

    public void setMySources(Source[] mySources) {
        this.mySources = mySources;
    }

    public void save() {
        ObjectsDAO odao = new ObjectsDAO();
        odao.save(myObjects);
    }
}

tabDefineObjects.xhtml:

<!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:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.org/ui"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head></h:head>
<body>
    <h:form id="form">

        <ui:param name="myeditobjects" value="#{editObjects}" />
        <p:dataTable var="object" value="#{myeditobjects.myObjects}" id="objectList" editable="true">

            <f:facet name="header">
                In-Cell Editing
            </f:facet>

            <p:column headerText="Name" style="width:30%">
                <p:cellEditor>
                    <f:facet name="output">
                        <h:outputText value="#{object.o_name}" />
                    </f:facet>
                    <f:facet name="input">
                        <p:inputText value="#{object.o_name}" style="width:100%"/>
                    </f:facet>
                </p:cellEditor>
            </p:column>
            <p:column headerText="Source" style="width:24%">
                <p:cellEditor>
                    <f:facet name="output">
                        <h:outputText value="#{object.sourceName}" />
                    </f:facet>
                    <f:facet name="input">
                        <h:selectOneMenu value="#{object.sourceName}" >
                            <f:selectItems value="#{myeditobjects.mySources}"
                                var="sources"
                                itemLabel="#{sources.s_name}"
                                itemValue="#{sources.s_name}" />
                        </h:selectOneMenu>
                    </f:facet>
                </p:cellEditor>
            </p:column>

            <p:column headerText="Description" style="width:20%">
                <p:cellEditor>
                    <f:facet name="output">
                        <h:outputText value="#{object.o_desc}" />
                    </f:facet>
                    <f:facet name="input">
                        <p:inputText value="#{object.o_desc}" style="width:100%" label="o_desc"/>
                    </f:facet>
                </p:cellEditor>
            </p:column>

            <p:column style="width:6%">
                <p:rowEditor />
            </p:column>
        </p:dataTable>
        <p:commandButton value="Submit" actionListener="#{myeditobjects.save()}" id="btnSubmit"/>    
    </h:form>
    </body>
</html>

Objects.java:

@Entity
@Table (name = "objects", schema="genmeta")
public class Objects {
    @Id
    @Column(unique=true, nullable=false)
    private int o_id;
    private String o_name;
    @ManyToOne
    @JoinColumn(name="s_id")
    private Source source;
    private String o_desc;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "object_tg_assc", joinColumns = { @JoinColumn(name = "o_id") }, inverseJoinColumns = { @JoinColumn(name = "tg_id") })
    private Set<TemplateGroup> templateGroups;
    @OneToMany(mappedBy="objects")
    private Set<ObjectTGAssc> objectTGAsscs;
    @OneToMany(mappedBy="object")
    private Set<ObjectAttribute> objectAttribute;
    @Transient
    private boolean newEntry = false;

    /**
     * Getters and Setters 
     */
    public int getO_id() {
        return o_id;
    }
    public void setO_id(int o_id) {
        this.o_id = o_id;
    }
    public String getO_name() {
        return o_name;
    }
    public void setO_name(String o_name) {
        this.o_name = o_name;
    }
    public String getSourceName() {
        return source.getS_name();
    }
    public void setSourceName(String name) {
        SourceDAO sdao = new SourceDAO();
        Source[] sources = sdao.getSourceList();
        for(Source source : sources) {
            if (source.getS_name().equals(name)) {
                this.source = source;
            }
        }
    }
    public String getO_desc() {
        return o_desc;
    }
    public void setO_desc(String o_desc) {
        this.o_desc = o_desc;
    }
    public Set<TemplateGroup> getTemplateGroups() {
        return templateGroups;
    }
    public void setTemplateGroups(Set<TemplateGroup> templateGroups) {
        this.templateGroups = templateGroups;
    }
    public Set<ObjectTGAssc> getObjectTGAsscs() {
        return objectTGAsscs;
    }
    public void setObjectTGAsscs(Set<ObjectTGAssc> objectTGAsscs) {
        this.objectTGAsscs = objectTGAsscs;
    }
    public Set<ObjectAttribute> getObjectAttribute() {
        return objectAttribute;
    }
    public void setObjectAttribute(Set<ObjectAttribute> objectAttribute) {
        this.objectAttribute = objectAttribute;
    }
    public boolean isNewEntry() {
        return newEntry;
    }
    public void setNewEntry(boolean newEntry) {
        this.newEntry = newEntry;
    }
}

ObjectsDAO.java:

public class ObjectsDAO {
    private static SessionFactory factory;

    public ObjectsDAO() {
        factory = Database.getSession();
    }

    /**
     * Gibt den gesuchten Attributtypen zurück
     * @param id Die zu suchende Id
     * @return Die gesuchte Spalte identifiziert anhand der ID
     */
    @SuppressWarnings("unchecked")
    public List<Objects> getAllObjects() {
        Session session = factory.openSession();
        List<Objects> myObjects = null;
        Query query = session.createQuery("from Objects");
        myObjects = query.list();
        session.close();
        return myObjects;
    }

    public void save(List<Objects> allObjects) {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            for(Objects curObject : allObjects) {
                if (curObject.isNewEntry()) {
                    session.save(curObject);
                } else {
                    session.update(curObject);
                }
            }
            tx.commit();
        } catch(HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

Sources.java:

@Entity
@Table (name = "source", schema="genmeta")
public class Source {
    @Id
    @Column(unique=true, nullable=false)
    private int s_id;
    private String s_name;
    @ManyToOne
    @JoinColumn(name="w_id")
    private Workspace workspace;
    private String s_desc;
    @OneToMany(mappedBy="source")
    private Set<Objects> objects;

    /**
     * Getters and Setters 
     */
    public int getS_id() {
        return s_id;
    }
    public void setS_id(int s_id) {
        this.s_id = s_id;
    }
    public String getS_name() {
        return s_name;
    }
    public void setS_name(String s_name) {
        this.s_name = s_name;
    }
    public Workspace getWorkspace() {
        return workspace;
    }
    public void setWorkspace(Workspace workspace) {
        this.workspace = workspace;
    }
    public String getS_desc() {
        return s_desc;
    }
    public void setS_desc(String s_desc) {
        this.s_desc = s_desc;
    }
    public Set<Objects> getObjects() {
        return objects;
    }
    public void setObjects(Set<Objects> objects) {
        this.objects = objects;
    }
}

SourcesDAO.java:

public class SourceDAO {
    private static SessionFactory factory;

    public SourceDAO() {
        factory = Database.getSession();
    }

    @SuppressWarnings("unchecked")
    public Source[] getSourceList() {
        Session session = factory.openSession();
        List<Source> mySources = null;
        Query query = session.createQuery("from Source");
        mySources = query.list();
        session.close();
        return mySources.toArray(new Source[0]);
    }
}

hibernate.cfg.xml中:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost/postgres</property>
        <property name="hibernate.connection.username">***</property>
        <property name="connection.password">***</property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">validate</property>

        <mapping class="db.hibernate.classes.Attributetype"/>
        <mapping class="db.hibernate.classes.Datatype"/>
        <mapping class="db.hibernate.classes.ObjectAttribute"/>
        <mapping class="db.hibernate.classes.Objects"/>
        <mapping class="db.hibernate.classes.ObjectSpecification"/>
        <mapping class="db.hibernate.classes.ObjectSpecificationType"/>
        <mapping class="db.hibernate.classes.ObjectTGAssc"/>
        <mapping class="db.hibernate.classes.Source"/>
        <mapping class="db.hibernate.classes.Template"/>
        <mapping class="db.hibernate.classes.TemplateTGAssc"/>
        <mapping class="db.hibernate.classes.TemplateGroup"/>
        <mapping class="db.hibernate.classes.TemplateType"/>
        <mapping class="db.hibernate.classes.Users"/>
        <mapping class="db.hibernate.classes.Workspace"/>
        <mapping class="db.hibernate.classes.WorkspaceUserAssc"/>
    </session-factory>
</hibernate-configuration>

非常感谢你的关注。

祝你好运 的Björn

2 个答案:

答案 0 :(得分:1)

您无需在此处添加onEdit方法。

您在datatable中所做的任何更改都将更新托管bean中的对象。

从xhtml中删除该行

        <p:ajax event="rowEdit" listener="#{myeditobjects.onEdit}" />

并从托管bean中删除上述方法。

现在,如果对数据表进行任何更改并调用save,您将看到对象已更新。

我希望有所帮助。

答案 1 :(得分:1)

您还没有为bean指定范围,默认情况下它将是@RequestScoped。为了支持对当前视图的请求并在请求之间保持当前视图状态,您应该至少使用@ViewScoped标记bean。

@ManagedBean
@ViewScoped
public class EditObjects implements Serializable {
}

更多信息: