How to get the specific property value from .prope

2019-07-30 08:48发布

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")

Instead of hard coding database names i.e., db1 and db2 here, I have to get them from properties file.

how to get the property value inside the @Query annotation in Spring Data JPA Repository ?

1条回答
ら.Afraid
2楼-- · 2019-07-30 09:20

I don't know if it is possible, but if not, you can consider this approach:

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);

}

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.

Happy hacking :)

查看更多
登录 后发表回答