2

I need to store Hibernate table name in Spring Boot application.properties file, so I can change it without code change. My code looks like :

    @Data
    @Entity
    @Table(name = "myTable")
    public class MySpecificTable{

        @Id
        private String someId;
    }
   @Repository
   public interface MySpecificRepository extends JpaRepository<MySpecificTable, String> {

        @Query(value = "SELECT * FROM myTable", nativeQuery = true)
        List<MySpecificTable> getCustom();
   }

I found this post which works pretty fine, but if I implement this configuration then I cannot use other default repository methods (getAll, findById etc), because this mapping strategy doesn't know how to map table name to default methods.

Is there any way to extract "myTable" to application.properties and use default repositories methods and have code something like this?

    @Data
    @Entity
    @Table(name = "${table.name.from.properties}")
    public class MySpecificTable{

        @Id
        private String someId;
    }
   @Repository
   public interface MySpecificRepository extends JpaRepository<MySpecificTable, String> {

        @Query(value = "SELECT * FROM " + getTableName() , nativeQuery = true)
        List<MySpecificTable> getCustom();
   }
Bohdan Myslyvchuk
  • 1,657
  • 3
  • 24
  • 39
  • 1
    Where it's possible I would suggest you to use jpa/hql queries (instead of native queries) it will allow you to use class name instead of table name. – SternK Jun 17 '20 at 10:17
  • 1
    nobody does this kind of stuff, this is an overengineering – improbable Jun 17 '20 at 11:37

0 Answers0