X
  • EJB
    January 4, 2011

Difference between EJB Persist & Merge operation

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 record

Let
us suppose that we have created Java EE Web Application with Entities
from Emp table

EJB_Entities.JPG








Create session bean & generate data control for the same
sessionbean.jpeg



Drop Emp Object(Expand SessionEJBLocal->Constructors under Data Controls) as ADF Parameter form in jspx page

Adf_form.jpeg



Drop persistEmp(Emp) as ADF CommandButton & provide
#{bindings.EmpIterator.currentRow.dataProvider} as the value for emp
parameter.

persistOperation.jpeg







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 record

Let 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.

form.jpeg

Drop mergeEmp(Emp) operation as commandButton & provide #{bindings.EmpIterator.currentRow.dataProvider} as the value for
emp parameter.

mergeOperation.jpeg

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]

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.