How do I configure JPA table name at runtime?

荒凉一梦 提交于 2019-12-04 10:55:19

For Hibernate 4.x, you can use a custom naming strategy that generates the table name dynamically at runtime. The server name could be provided by a system property and so your strategy could look like this:

public class ServerAwareNamingStrategy extends ImprovedNamingStrategy {

    @Override
    public String classToTableName(String className) {
        String tableName = super.classToTableName(className);
        return resolveServer(tableName);
    }

    private String resolveServer(String tableName) {
        StringBuilder tableNameBuilder = new StringBuilder();

        tableNameBuilder.append(tableName);
        tableNameBuilder.append("_");
        tableNameBuilder.append(System.getProperty("SERVER_NAME"));

        return tableNameBuilder.toString();
    }
}

And supply the naming strategy as a Hibernate configuration property:

<property 
    name="hibernate.ejb.naming_strategy" 
    value="my.package.ServerAwareNamingStrategy"
/>

I would not do this. It is very much against the grain of JPA and very likely to cause problems down the road. I'd rather add a layer of views to the tables providing unified names to be used by your application.

But you asked, so have some ideas how it might work:

  1. You might be able to create the mapping for your classes, completely by code. This is likely to be tedious, but gives you full flexibility.

  2. You can implement a NamingStrategy which translates your class name to table names, and depends on the instance it is running on.

  3. You can change your code during the build process to build two (or more) artefacts from one source.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!