Search code examples
javahibernatelogicunique-key

Java unique code generation failed while calling the recurring function


We have to implement a logic to write the unique code generation in Java. The concept is when we generate the code the system will check if the code is already generate or not. If already generate the system create new code and check again. But this logic fails in some case and we cannot able to identify what is the issue is

Here is the code to create the unique code

Integer code = null;

try {
    int max = 999999;
    int min = 100000;
    code = (int) Math.round(Math.random() * (max - min + 1) + min);
    PreOrders preObj = null;
    preObj = WebServiceDao.getInstance().preOrderObj(code.toString());
    if (preObj != null) {
        createCode();
    }

} catch (Exception e) {
    exceptionCaught();
    e.printStackTrace();
    log.error("Exception in method createCode() - " + e.toString());
}
return code;

}

The function preOrderObj is calling a function to check the code exists in the database if exists return the object. We are using Hibernate to map the database functions and Mysql on the backend.

Here is the function preOrderObj

PreOrders preOrderObj = null;
        List<PreOrders> preOrderList = null;
        SessionFactory sessionFactory =
                (SessionFactory) ServletActionContext.getServletContext().getAttribute(HibernateListener.KEY_NAME);
        Session Hibernatesession = sessionFactory.openSession();
        try {
            Hibernatesession.beginTransaction();
            preOrderList = Hibernatesession.createCriteria(PreOrders.class).add(Restrictions.eq("code", code)).list(); // removed .add(Restrictions.eq("status", true))
            if (!preOrderList.isEmpty()) {
                preOrderObj = (PreOrders) preOrderList.iterator().next();
            }
            Hibernatesession.getTransaction().commit();
            Hibernatesession.flush();
        } catch (Exception e) {
            Hibernatesession.getTransaction().rollback();
            log.debug("This is my debug message.");
            log.info("This is my info message.");
            log.warn("This is my warn message.");
            log.error("This is my error message.");
            log.fatal("Fatal error " + e.getStackTrace().toString());
        } finally {
            Hibernatesession.close();
        }
        return preOrderObj;
    }

Please guide us to identify the issue.


Solution

  • In createCode method, when the random code generated already exist in database, you try to call createCode again. However, the return value from the recursive call is not updated to the code variable, hence the colliding code is still returned and cause error.

    To fix the problem, update the method as

    ...
        if (preObj != null) {
            //createCode();
            code = createCode();
        }  
    ...
    

    Such that the code is updated. By the way, using random number to generate unique value and test uniqueness through query is a bit strange. You may try Auto Increment if you want unique value.