Home » Java » java – How to create property to define different schema name with universal prefix?-Exceptionshub

java – How to create property to define different schema name with universal prefix?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

The problem is that I have a lot of nativeQueries where I use schema name prefix to define table which I want to use.

For example:

SELECT * FROM SCHEMA.USERS u WHERE u.id = 100;

The problem is that now I have 2 database with the same tables but different schema names.

DB1: SCHEMA_1.USERS
DB2: SCHEMA_2.USERS

Is this possible to create property for hibernate where I can define that SCHEMA_1 and SCHEMA_2 will be known as SCHEMA? As I checked, Oracle SYNONYM is not working for schemas..

How to&Answers:

According to the hibernate documentation

When using multiple database catalogs and schemas, Hibernate offers the possibility of setting a global catalog or schema so that you don’t have to declare it explicitly for every entity.

<property name="hibernate.default_catalog" value="crm"/>
<property name="hibernate.default_schema" value="analytics"/>

and further:

However, for native queries, the SQL query is passed as is, therefore you need to explicitly set the global catalog and schema whenever you are referencing a database table. Fortunately, Hibernate allows you to resolve the current global catalog and schema using the following placeholders:

{h-catalog} – resolves the current hibernate.default_catalog configuration property value.

{h-schema} – resolves the current hibernate.default_schema configuration property value.

{h-domain} – resolves the current hibernate.default_catalog and hibernate.default_schema configuration property values (e.g. catalog.schema).

So, you can avoid the explicit mention the schema name in your native sql:

SELECT * FROM {h-schema}USERS u WHERE u.id = 100;

But as for your question:

Is this possible to create property for hibernate where I can define that SCHEMA_1 and SCHEMA_2 will be known as SCHEMA?

I guess it’s impossible to do with using only standard hibernate functionality.

Answer:

I am not from Hibernate background, so I don’t know if there is any native way to do this in Hibernate itself. In pure Oracle method, when you connect to the database, get the current schema name and assign it to a variable and then use it in the SQL statement.

select sys_context( 'userenv', 'current_schema' ) as SCHEMA from dual;

The above output you could assign to the SCHEMA variable in your Hibernate application code(again I am not sure what is the Hibernate method of using a variable so assume $ for now):

SELECT * FROM $SCHEMA.USERS u WHERE u.id = 100;

So, when you connect to DB1, you will get schema name let’s say SCHEMA_1 and then from DB2 you will get SCHEMA_2. But these values will be assigned to $SCHEMA variable so you need not worry about changing it as it will dynamically take the schema name.