使用应用程序属性文件在本机查询中选择 table 名称?

Use application properties file to pick the table name in a native query?

我在我的 Spring 引导应用程序中使用本机查询,我希望能够从我的属性文件中选择 table 名称。我尝试使用 spel 表达式,它确实使用了 @Entity 注释中指定的 table 名称......但是我想使用 @Value(${table.name} 之类的东西将字符串“bookshelf”注入到 Entity 注释中有道理。

我还尝试了一种不同的方法,使用休眠中的物理命名策略,但它似乎并没有取代 table 名称。

实体class:

   @Entity(name = "bookshelf")
   public class Object{
   
   private String color;
   private String shape;
}

存储库:

@Repository
public interface ObjectRepository extends CrudRepository<Object,Long>{

@Query(nativeQuery = true, value = "select color from #{#entityName} where shape =: shape)
public List<Object> findObjectsByShape(@Param("shape") String shape);

application.yml

table:
  name: bookshelf

我怎样才能做到这一点?

据我所知,你不能用注释来做到这一点。

你能做什么:

注入 EntityManager,例如:

@PersistenceContext
EntityManager em;

在 em 上你可以打电话

em.createNativeQuery("your native query")

哪里可以使用您可以在 class 中访问的任何值。

但是:请注意,这可能是对您的应用程序发起 sql 注入攻击的第一步。如果除了动态构建查询之外还有其他方法可以实现您的目标,请采用其他方法。

从安全动态传递 table 名称不是好的做法 perspective.It 在 Hibernate 中是不可能的,但是如果仍然需要,您可以使用 Eclipse-Link 实现,

String tableName = "tablename";
String query = "SELECT * FROM " +tablename +"WHERE salary > 10000";