I'm having a bit of trouble with one particular issue using JPA/Spring:
How can I dynamically assign a schema to an entity?
We have TABLE1 that belongs to schema AD and TABLE2 that is under BD.
@Entity @Table(name = "TABLE1", schema="S1D") ... @Entity @Table(name = "TABLE2", schema="S2D") ...
The schemas may not be hardcoded in an annotation attribute as it depends on the environment (Dev/Acc/Prd). (In acceptance the schemas are S1A and S2A)
How can I achieve this? Is it possible to specify some kind of placeholders like this:
@Entity @Table(name = "TABLE1", schema="${schema1}") ... @Entity @Table(name = "TABLE2", schema="${schema2}") ...
so that schemas are replaced based on a property file residing in the environment?
Cheers
In the Oracle database system, the term database schema, which is also known as "SQL schema," has a different meaning. Here, a database can have multiple schemas (or “schemata,” if you're feeling fancy). Each one contains all the objects created by a specific database user.
Multiple Databases in Spring Boot The interesting part is annotating the data source bean creation method with @ConfigurationProperties. We just need to specify the corresponding config prefix. Inside this method, we're using a DataSourceBuilder, and Spring Boot will automatically take care of the rest.
Until now with spring 4 and XML configuration I was able to only put the DB URL like: jdbc:mysql://180.179.57.114:3306/?zeroDateTimeBehavior=convertToNull and in the entity class specify the schema to use and thus able to connect to multiple schemas.
I had the same problem I solved that with a persistence.xml in which I refer to the needed orm.xml files within I declared the db shema
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0" > <persistence-unit name="schemaOne"> . . . <mapping-file>ormOne.xml</mapping-file> . . . </persistence-unit> <persistence-unit name="schemaTwo"> . . . <mapping-file>ormTwo.xml</mapping-file> . . . </persistence-unit> </persistence>
now you can create a EntityManagerFactory for your special schema
EntityManagerFactory emf = Persistence.createEntityManagerFactory("schemaOne");
One thing you can do if you know at deployment is to have 2 orm.xml files. One for schema1 and one for schema2 and then in the persistence.xml you have 2 persistence-units defined. Putting annotations is an anti-pattern if needing to change things like schema
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With