我知道在JPA查询中动态修改表名和列名是不可能的。它们必须是硬编码的。
但是,我有一个模式,它有许多不同的表,前三列都具有相同的结构。我不想知道是否有使用变量修改表名和列名的捷径,而不必编写一个类或方法来查询其中的每一个。我现有的查询如下所示:
public interface ExampleRepository extends JpaRepository<Example, Long>,
JpaSpecificationExecutor<Example> {
@Query(value = "SELECT name_ln FROM ?1 WHERE ?2 = ?3",
nativeQuery = true)
String getName(String tableLookUp, String idColumn, long namespaceRefId);
}这不起作用,由于表名和列名用引号括起来,MySQL会产生以下错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''table_name' WHERE 'column_id' = 211833' at line 1发布于 2019-11-26 16:51:35
您可以尝试使用Param注释将值传递到查询中。
例如:
@Query(value = "SELECT name_ln FROM :tableName WHERE :columnName = :value", nativeQuery = true)
String getName(@Param("tableName") String tableLookUp, @Param("columnName") String idColumn, @Param("value") long namespaceRefId);确保查询结果将是单个记录。这可能会导致错误。
https://stackoverflow.com/questions/39143444
复制相似问题