1

When I use IntelliJ to generate a persistence mapping from exisitng database schema it puts a catalog value as part of @Table annotation. Unfortunately names of database instances have names of dev/test/prod environemnts in them and while I can overwrite the connection string with a map passed to EntityManagerFactory I still get Invalid object name 'BAR_DEV.dbo.FOO' when executing a query against BAR_TEST instance.

Can I dynamically overwrite the catalog value at runtime without doing global search and replace to remove it manually after entity generation?

@Entity
@Table(name = "FOO", schema = "dbo", catalog = "BAR_DEV")
public class Foo{ /* ... */ }
OndroMih
  • 7,280
  • 1
  • 26
  • 44
Ilya Kozhevnikov
  • 10,242
  • 4
  • 40
  • 70

2 Answers2

1

No, it is not possible directly with standard JPA.

However, a solution I used in my project was to define multiple persistence units, each for a particular environment. You may overwrite any database mapping in an orm.xml file, or even set default catalog or schema for all entities. Next step is to dynamically retrieve proper EntityManager - if you are using Java EE, I recomment injecting using @Inject and creating a producer, which returns particular EM for specified environment.

OndroMih
  • 7,280
  • 1
  • 26
  • 44
0

Non portable, Eclipselink only org.eclipse.persistence.dynamic.DynamicHelper.SessionCustomizer can replace many defaults at runtime.

EDIT: I haven't ready code for You. I use this way

    public void customize(Session session) throws SQLException {
        ...
    for (ClassDescriptor descriptor : session.getDescriptors().values()) {

                if (!descriptor.getTables().isEmpty() && descriptor.getAlias().equalsIgnoreCase(descriptor.getTableName())) {
            tableName = TABLE_PREFIX + clazz.getSimpleName();
  descriptor.setTableName(tableName);
    }
    }
Jacek Cz
  • 1,872
  • 1
  • 15
  • 22