This article gives the difference between EJB Persist & Merge operations with scenarios.Use Case Description
Users working on EJB persist & merge operations often have
this question in mind " When merge can create new entity as well as
modify existing entity,then why do we have 2 separate operations -
persist & merge?" The reason is very simple.If we use merge
operation to create new entity & if the entity exists then it does
not throw any exception,but persist throws exception if the entity
already exists.Merge should be used to modify the existing entity.The
sql statement that gets executed on persist operation is insert
statement.But in case of merge first select statement gets executed
& then update sql statement gets executed.Scenario 1: Persist operation to create new Emp recordLet
us suppose that we have a Java EE Web Application created with Entities
from Emp table & have created session bean with data control. Drop Emp Object(Expand SessionEJBLocal->Constructors under Data Controls) as ADF Parameter form in jspx pageDrop persistEmp(Emp) as ADF CommandButton & provide
#{bindings.EmpIterator.currentRow.dataProvider} as the value for emp
parameter.Then run this page & provide values for Emp,click on 'persistEmp' button.New Emp record gets created.So when we execute persist operation only insert sql statement gets executed :INSERT INTO EMP (EMPNO, COMM, HIREDATE, ENAME, JOB, DEPTNO, SAL, MGR) VALUES (?, ?, ?, ?, ?, ?, ?, ?) bind => [2, null, null, e2, null, 10, null, null]Scenario 2: Merge operation to modify existing Emp recordLet us suppose that we have a Java EE Web Application created with
Entities from Emp table & have created session bean with data control.Drop empFindAll() Object as ADF
form on jspx page.Drop mergeEmp(Emp) operation as commandButton & provide #{bindings.EmpIterator.currentRow.dataProvider} as the value for
emp parameter.Then run this page & modify values for Emp record,click on
'mergeEmp' button.The respective Emp record gets modified.So when we execute merge operation select & update sql statements gets executed :SELECT EMPNO, COMM, HIREDATE, ENAME, JOB, DEPTNO, SAL, MGR FROM EMP WHERE (EMPNO = ?) bind => [7566]UPDATE EMP SET ENAME = ? WHERE (EMPNO = ?) bind => [KINGS, 7839]