在Spring Data MongoRepository中构建搜索端点可以通过以下步骤实现:
import org.springframework.data.mongodb.repository.MongoRepository;
public interface UserRepository extends MongoRepository<User, String> {
}
import org.springframework.data.mongodb.repository.MongoRepository;
public interface UserRepository extends MongoRepository<User, String> {
List<User> findByFirstName(String firstName);
}
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@Configuration
@EnableMongoRepositories(basePackages = "com.example.repository")
public class MongoConfig {
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/users")
public List<User> searchUsers(@RequestParam String firstName) {
return userRepository.findByFirstName(firstName);
}
}
以上步骤完成后,可以通过发送GET请求到/users
端点,并传递firstName
参数来执行搜索操作。例如,发送GET请求到/users?firstName=John
将返回所有名为John的用户。
对于Spring Data MongoRepository的更多详细信息和用法,请参考腾讯云MongoDB产品的文档:Spring Data MongoDB
领取专属 10元无门槛券
手把手带您无忧上云