JPA using Schema variable name in annotations

I am using the Java Persistence API to describe tables from my database that I will be manipulating in my code.

However, the schema used will not be the same depending on where my project is installed. So when I use annotations I would like the SCHEMA field to be a variable, but I cannot do that:

@Entity
@Table(name = "TABLE_NAME", schema = schemaVariable, catalog = "")

      

How can I achieve this? Is this possible with persistence.xml file ?

+3


source to share


3 answers


No, It is Immpossible. Only compile-time constants (all primitives and String

) can be used in annotations .

You can use final variables:

public class DatabaseMetadata {
    public static final SCHEMA = "MySchema";
}

      

and then use it in annotation:



@Table(name = "TABLE_NAME", schema = DatabaseMetadata.SCHEMA, catalog = "")

      

but i think this is not what you wanted.

PS. On the other hand, examples of use can be found in annotations, i.e. Spring EL (see annotation @Value

), but it requires a dedicated annotation handler. AFAIK none of the JPA

providers give you that leeway.

+1


source


Putting schema information (like tables, columns, schema names) in java classes is a bad idea anytime IMHO (forced recompilation if you want to deploy elsewhere). You can put this information in orm.xml

and just deploy another one orm.xml

depending on your deployment requirement.



As for persistence.xml

, you will depend on your JPA provider having a persistence property that defined the default schema / directory. I know DataNucleus JPA (which I am using) has this, but dont know for Hibernate

0


source


If you know you are using different schemas I would suggest using 2 mapping files and define

<entity-mappings> 
    <persistence-unit-metadata> 
       <persistence-unit-defaults> 
          <schema>HR</schema> 
       </persistence-unit-defaults> 
    </persistence-unit-metadata> 
... 
</entity-mappings> 

      

This way, you can easily modify the schemas without any changes to the application code.

0


source







All Articles