Sample UseCase:
Let's take a simple example to create a duplicate record of an existing employee record. First, the user searches for the employee and selects the employee record from the search results and clicks on button 'Duplicate Record' to duplicate the selected record. And, then the search results table will be refreshed with the newly created (in other words duplicated) row (could be identified by '_DUP' suffix). You can select the record and click on 'View Record' to see the data of the record.
Implementation:
Below is the simple method that duplicates the current emp row.
public void duplicateEmpRecord() { ViewObjectImpl empVO = this.getEmpDeptVO(); Row empCurrentRow = empVO.getCurrentRow(); String[] empAttrs = empCurrentRow.getAttributeNames(); //Skip copying the primay key attributes or any attributes which you want to skip String[] skipAttrs = new String[] { "Empno", "Ename" }; List skipAttrList = Arrays.asList(skipAttrs); //creating a new duplicate row Row dupRow = empVO.createRow(); //copying all attributes one by one for (int i = 0; i < empAttrs.length; i++) { String empAttrName = empAttrs[i]; //For demo purpose, just adding '-DUP' suffix for the original Emp Name. if ("Ename".equals(empAttrName)) dupRow.setAttribute(empAttrName, empCurrentRow.getAttribute(empAttrName) + "_DUP"); int attrIndex = dupRow.getAttributeIndexOf(empAttrName); //Checking if the attribute is in the skip attribute list and the attribute is updatable if (!skipAttrList.contains(empAttrName) && dupRow.isAttributeUpdateable(attrIndex)) //Setting the value for the attributes dupRow.setAttribute(empAttrName, empCurrentRow.getAttribute(empAttrName)); } //Inserting the duplicate row empVO.insertRow(dupRow); }
Explanation: In the above code, we're getting the Emp current row and getting attribute names for the row and iterating through these attributes, to set the attribute values to the newly created row(duplicate row). This will avoid manually specifying each and every attribute name to copy manually. And one thing to note here is that all attributes in the VO may not be updatable. So, we're checking whether a particular attribute in the VO is updatable and setting the value for it only if it's updatable. And, we want to avoid setting values for primary key attributes and unique attributes because setting the same value for these attributes will through 'too many objects match the priamry key...' exception. To avoid that, we're maintaining a list of attributes which we want to skip setting the values. You can see the if condition in the loop. We will be setting values for these attributes manually.
So, this method of copying all attributes to new row is automatic and efficient as we're not manually setting attribute values one by one.
Hope, this would be helpful.

