i've created a web-application in which i've to submit a form for which there will be a serial number generated , on submission serial number should be given to only for one registration, say if two application submit at the very same instance there will be chance of getting duplicate serial number for the two registration.
i've wrote a code which is as given below, can we prevent the above mentioned problem using this code, please give valuable suggestion on this.
public String registration(){
Session session = factory.openSession();
Transaction t = null;
try {
t = session.beginTransaction();
TableSerialGenerator serialnoObj;
serialnoObj=generateSerialNo("1", session);
String Serial_No=serialnoObj.getPrefix()+"-"+serialnoObj.getCurrentIndex();
Registration res=new Registration(Serial_No,......);
session.save(res);
t.commit();
return SUCCESS;
}
catch (RuntimeException e) {
if(t!= null)
t.rollback();
return ERROR;
}
finally {
session.close();
}
}
public TableSerialGenerator generateSerialNo(String type,Session session)
{
String serialno="";
TableSerialGenerator obj=new TableSerialGenerator();
try
{
obj=(TableSerialGenerator) session.get(TableSerialGenerator.class, Integer.parseInt(type), LockMode.UPGRADE);
if(obj.getCurrentIndex() == null)
{
obj.setCurrentIndex(obj.getStartIndex());
}
else
{
obj.setCurrentIndex(obj.getCurrentIndex()+1);
}
session.save(obj);
}
catch(Exception e)
{
System.out.println("Exception in generateSerialNo method of CommonHibernateClass class....."+e);
e.printStackTrace();
}
return obj;
}
TableSerialGenerator.java
public class TableSerialGenerator implements java.io.Serializable {
private Integer id;
private String prefix;
private String suffix;
private Integer startIndex;
private String type;
private Integer currentIndex;
private String status;
private Date createdDate;
private Date modifiedDate;
//getters and setters
}