问题描述
我能够在 Spring 类中获取属性值,如下所示:
I am able to get the property value in Spring classes like below:
@Value("${database.name}")
private String databaseName;
我必须通过连接不同数据库中的不同表来执行本机查询.
I have to execute a native query by joining different tables which are in different databases.
@Query(value="select t1.* FROM db1.table1 t1 INNER JOIN db2.table2 t2 ON t2.t1_id1 = t1.id1")
这里不是硬编码数据库名称,即 db1 和 db2,我必须从属性文件中获取它们.
Instead of hard coding database names i.e., db1 and db2 here, I have to get them from properties file.
如何获取Spring Data JPA Repository中@Query注解内的属性值?
how to get the property value inside the @Query annotation in Spring Data JPA Repository ?
推荐答案
不知道可不可以,如果不行,可以考虑这样的做法:
I don't know if it is possible, but if not, you can consider this approach:
您可以在查询中使用参数而不是直接使用 Repository 的 @Query
中的属性,但是当您调用实际方法时 - 您可以提供来自 .properties
的值.
Instead of using properties in Repository's @Query
directly, you can use params in the query but when you call the actual method - you can provide values from .properties
.
假设您有一个简单的存储库:
Imagine you have simple repository:
public interface UserRepository extends JpaRepository<User, Long> {
// query with param
@Query("select u from User u where u.lastname = :lastname")
User findByLastname(@Param("lastname") String lastname);
}
然后,假设您有一些 Service
或 Controller
需要在其中使用 Repository
- 您可以在那里注入属性并传递它们到您的方法:
Then, let's say you have some Service
or Controller
where you need to use your Repository
- you can inject properties there and pass them to your method:
@Service
public class UserService {
// this comes from .properties
@Value("${user.lastName}")
private String userLastName;
@Autowired
private UserRepository userRepository;
public User getUser() {
// you pass it as param to the repo method which
// injects it into query
return userRepository.findByLastname(userLastName);
}
}
这只是一个例子.但我相信它可能有用.
This is just an example. But I believe it may be useful.
快乐黑客:)
这篇关于如何从Spring Data Repository接口方法@Query中的.properties文件中获取特定的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!