Search code examples
springspring-bootspring-data-jdbc

unable to get custom NamingStrategy working


my Spring application has to read from a table called MY_DOMAIN_OBJECT which belongs to MY_CUSTOM_SCHEMA schema, note that the same table is present in the default schema as well.

I'm using spring-data-jdbc but I'm not able to read from the right schema. I'm creating a custom NamingStrategy bean with some method overrides but with no success, the outcome is that I get results from the table in the default schema.

Any idea of what I am doing wrong here?

Below the relevant classes:

AppConfig.java

@Configuration
@EnableJdbcRepositories(basePackages = "my.package.for.persistence")
public class AppConfig extends JdbcConfiguration {

    @Bean(name = "sourceDS", destroyMethod = "")
    public DataSource sourceDatasource() {
        JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
        return dataSourceLookup.getDataSource("jdbc/OracleDS");
    }

    @Bean
    public NamedParameterJdbcOperations operations() {
        return new NamedParameterJdbcTemplate(sourceDatasource());
    }

    @Bean
    //@Primary
    public NamingStrategy namingStrategy() {
        return new NamingStrategy() {

            @Override
            public String getTableName(Class<?> type) {
                return type.isAnnotationPresent(Table.class) ?
                        type.getAnnotation(Table.class).value() : NamingStrategy.super.getTableName(type);
            }

            @Override
            public String getQualifiedTableName(Class<?> type) {
                return type.isAnnotationPresent(Table.class) ?
                        type.getAnnotation(Table.class).value() : NamingStrategy.super.getTableName(type);
            }

            @Override
            public String getSchema() {
                return "my_custom_schema";
            }


        };
    }
}

MyDomainObject.java

package my.package.for.persistence;

@Data
@AllArgsConstructor
@Table("MY_DOMAIN_OBJECT")
public class MyDomainObject{

    @Id
    private Long id;

    //other fields
}

MyRepository.java

package my.package.for.persistence;

public interface MyRepository extends Repository<MyDomainObject, Long> {

    Stream<MyDomainObject> findAll();
}

UPDATE: i forgot to mention that I'm using the spring-boot-starter-data-jdbc and I suspect this is causing the issue.


Solution

  • Oh sorry, I should have seen that way sooner.

    Don't overwrite getQualifiedTableName the default implementation does the combining of the table and the schema name.