Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I configure JPA table name at runtime?

I have an issue where I have only one database to use but I have multiple servers where I want them to use a different table name for each server.

Right now my class is configured as:

@Entity
@Table(name="loader_queue")
class LoaderQueue

I want to be able to have dev1 server point to loader_queue_dev1 table, and dev2 server point to loader_queue_dev2 table for instance.

Is there a way i can do this with or without using annotations?

I want to be able to have one single build and then at runtime use something like a system property to change that table name.

like image 573
Rocky Pulley Avatar asked Mar 15 '23 15:03

Rocky Pulley


1 Answers

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"
/>
like image 185
Vlad Mihalcea Avatar answered Mar 27 '23 10:03

Vlad Mihalcea