简体   繁体   中英

How to implement a save Button in Primefaces

i wrote a form in primefaces, where I want to show and change my data in my database. Now I want to make it, that the user could change the data in frontend, and could make it undo, if he reload the page. On this page should be a save button, and only if this button was pushed, the data should be saved in database.

Currently I got the problem, if I run the onSave Method, I can't see the variables of my previous function onEdit. So I wrote only the wrong data into database.

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>

Thanks a lot of your attention.

Best regards Björn

You do not need to add onEdit method here.

Any changes you make in the datatable will update the object in managed bean.

Delete the line from your xhtml

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

and remove the above method from your managed bean.

Now if make any changes to the datatable and call save,you'll see the objects are updated.

I hope that helps.

You haven't specified a scope for your bean, by default it will be @RequestScoped . To support requests made to the current view and keep the current view state across requests, you should mark your bean with @ViewScoped at least.

@ManagedBean
@ViewScoped
public class EditObjects implements Serializable {
}

More info:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM