Search code examples
oraclehibernate

How to get nextval of dynamic sequence


I have tried to optimize my code and use a shared method for the cases where I need to get sequence nextval for multiple sequences in my application. But when I tried to do it as clean and safe as possible it is not working.

Working but not safe :

Query q = em.createNativeQuery("SELECT " + seqName + ".NEXTVAL FROM DUAL");

Safe but not working :

Query q = em.createNativeQuery("SELECT :SEQ_NAME.NEXTVAL FROM DUAL");
q.setParameter("SEQ_NAME", seqName);

Do you know how to write this better ? Thanks.


Solution

  • With Oracle, you have to reference the sequence as a literal name. What makes your current version unsafe is the possibility to inject SQL in the sequence name. Couldn't you add a verification in the method that the sequence name contains only letters, numbers, dots and perhaps underscores, and the current could would actually be safe...?

    if(!seqName.matches("[A-Za-z._]+"))
      throw new IllegalArgumentException("Invalid sequence name: " + seqName);