I need to dynamically create new sequences in my database but for some reason it’s just not working when I use parameters (named or ordinal). My code for this is quite simple (em
= jakarta.persistence.EntityManager
)
var createSeqSql = "CREATE SEQUENCE IF NOT EXISTS :seqName AS INTEGER;";
Query createQuery = em.createNativeQuery(createSeqSql);
createQuery.setParameter("seqName", "some_seq_name");
createQuery.executeUpdate();
This fails with an exception
org.postgresql.util.PSQLException: ERROR: syntax error at or near “$1”
Position: 31
Position 31 is
CREATE SEQUENCE IF NOT EXISTS :seqName AS INTEGER;
^ here
If I set a breakpoint and look into the parameter binding map of Hibernate’s NativeQueryImpl
I can see that the parameter seqName
has been bound to the value some_seq_name
, so what gives?
The weird thing is, if I use string interpolation (which I don’t want to, as it’s vulnerable to SQL injection) it works. I.e.
var createSeqSql = String.format("CREATE SEQUENCE IF NOT EXISTS %s AS INTEGER;", seqName);
Query createQuery = em.createNativeQuery(createSeqSql);
createQuery.executeUpdate();
So why does string interpolation work, but parameter binding not work?
5