Each record in the database have an unique number
i.e, for record A unique number is 123
fore record B unique number is 124
This unique number is generated from a table and after assigning the unique number generated to record(here consider the record as patient record) it will be incremented by one.
Refer to the java snippet code below:
//Private EntityManager em//
//Control File is Entity name whose table name is control_master//
//em.CreateQuery is Java Persistence API Query//
seqQuery = em.createQuery(" SELECT c FROM ControlFile c WHERE c.instCode =:instCode and c.controlType=:controlType").setParameter("instCode",instStringCode).setParameter("controlType",ctrlType.trim() );
For the above query consider my instCode as 100 and controlType as NUMBER.
My table data will be as follows
S.No InstCode ControlType ControlNumber
1 100 NUMBER 25
2 200 NUMBER 570
3 253 NUMBER 32145
lastNo=controlFile.getCtrlLastNo();
/**So for Inst code=100 and Control Type=Number lastNo=25**/
controlFile.setCtrlLastNo(lastNo+1);
em.merge(controlFile);
em.flush();
/**Updation in the Database Completed**//
This what we have done initially .But as the number of concurrent users who are using the table has got increased i.e, when one more than one user is using the above query at the same time it give me the same control file number for me so because of this i had lost the uniqueness of my records because for two users it is giving the same number.
So we have a written a query so that a row level lock is created on the row which we are accessing.
/**Java Snippet Code which provides Rowlevel Locking on the database row**//
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public Long NumGn(EntityManager em, Long instCode,String ctrlType) throws Exception{
/*This select for update create a read lock for the second or more users when a particular row is read by the first user .The lock will be released at the end of the transaction.Then the next user can read the row and it creates a lock for all other users .As one user only can access a particular row at a time the query execution will give a unique number and my problem has got rectified*/
Query query=em.createNativeQuery(" SELECT ctrl_id, ctrl_type, ctrl_last_no, inst_code FROM control_file WHERE ((inst_code = ?1) AND (ctrl_type = ?2)) FOR UPDATE",ControlFile.class).setParameter("1", instStringCode).setParameter("2",ctrlType.trim());lastNo=controlFile.getCtrlLastNo();
em.merge(controlFile);
em.flush();}
No comments:
Post a Comment