I have a multi-tenant application using schemas to separate tenants. My connection pool does not support multi-tenant out-of-the-box (Dropwizard) - so I am trying to set the tenant's schema manually on retrieval. However, I am getting an SQL syntax error.
Code:
NativeQuery fpq = this.getSessionFactory()
.getCurrentSession()
.createNativeQuery("SET schema=?");
fpq.setParameter(1, tenantSchema);
fpq.executeUpdate();
Error:
DEBUG org.hibernate.SQL: SET schema=?
TRACE org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [1] as [VARCHAR] - [myapplication_client1]
WARN org.hibernate.engine.jdbc.spi.SqlExceptionHelper: SQL Error: 0, SQLState: 42601
ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper: ERROR: syntax error at or near "$1"
Position: 12
I've also tried "SET search_path=?" and "SET search_path TO ?" with the same result. This seems pretty straight forward, what am I doing wrong? The tenantSchema variable is generated using an untrustworthy string, so it is important to build the parameters correctly and not manually concat the SQL.
Update: Stepping through the debugger, I have verified Hibernate is correctly converting the statement to SET schema 'myapplication_client1' - but it still fails, I don't know why. It definitely has something to do with setParameter since the query runs fine if I hard-code it.
schemae.g.select colA from myschema.mytable;