1

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

}
4

1 回答 1

0

为了避免可能出现的多线程问题,您可以在获取序列号的方法中使用 syncronized 关键字 "generateSerialNo" ,这样可以避免两次获取相同的序列号。但是 JPA 中有一个策略可以用来获取新的序列值,如果你想使用表考虑使用@TableGenerator。

@TableGenerator(
            name="empGen", 
            table="ID_GEN", 
            pkColumnName="GEN_KEY", 
            valueColumnName="GEN_VALUE", 
            pkColumnValue="EMP_ID", 
            allocationSize=1)
        @Id
        @GeneratedValue(strategy=TABLE, generator="empGen")
        int id;

这将在每个保存操作中为特定实体创建一个新的序列号。

表生成器 API

于 2014-01-24T23:58:13.257 回答