How to get the specific property value from .properties file in Spring Data Repository interface method @Query

后端 未结 1 1215
终归单人心
终归单人心 2021-01-24 12:02

I am able to get the property value in Spring classes like below:

@Value(\"${database.name}\")
private String databaseName;

I have to execute a

相关标签:
1条回答
  • 2021-01-24 12:11

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

    0 讨论(0)
提交回复
热议问题