SpringCloud 创建JPA存储库

在上一节中,我们创建了一个表内存数据库,并看到正确填充了所有数据。在本节中,我们将创建一个返回服务响应的存储库。

步骤1: 创建一个名称为 ExchangeValueRepository 的接口并扩展 JpaRepository 类。我们必须传递 两个参数: 它管理的实体的类型和ID的 类型字段。

public interface ExchangeValueRepository extends JpaRepository<ExchangeValue, Long>

步骤2: 打开 CurrencyExchageController.java 文件并自动连接 ExchageValueRepository

@Autowired
private ExchangeValueRepository repository;

步骤3: ExcahngeValueRepository.java 文件中创建 查询方法

ExchangeValue findByFromAndTo(String from, String to);

在上面的语句中, ExchangeValue 是预期的响应。我们必须找到 两个列:

如果我们想在根据单列,我们可以传递一个列名。例如:

ExchangeValue findByFrom (String from);

ExcahngeValueRepository.java

package com.aizws.microservices.currencyexchangeservice;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ExchangeValueRepository extends JpaRepository<ExchangeValue, Long>
{
//creating query method
ExchangeValue findByFromAndTo(String from, String to);
}

步骤4: CurrencyExchangeController.java 中,使用以下语句:

ExchangeValue exchangeValue=repository.findByFromAndTo(from,to);

代替使用以下语句:

ExchangeValue exchangeValue=new ExchangeValue(1000L, from, to, BigDecimal.valueOf(65));

CurrencyExchangeController.java

package com.aizws.microservices.currencyexchangeservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController 
public class CurrencyExchangeController 
{
@Autowired
private Environment environment;
@Autowired
private ExchangeValueRepository repository;
@GetMapping("/currency-exchange/from/{from}/to/{to}")      //where {from} and {to} are path variable
public ExchangeValue retrieveExchangeValue(@PathVariable String from, @PathVariable String to)   //from map to USD and to map to INR
{       
ExchangeValue exchangeValue = repository.findByFromAndTo(from, to);
//setting the port
exchangeValue.setPort(Integer.parseInt(environment.getProperty("local.server.port")));
return exchangeValue;
}
}

步骤5: 重新启动应用程序以获取更改。打开浏览器,然后输入URI http://localhost:8000/currency-exchange/from/USD/to/INR 。它返回以下响应:

创建JPA存储库

我们还可以尝试其他方法通过将URI中的货币 USD 更改为 EUR 进行转换。

http://localhost:8000/currency-exchange/from/EUR/to/INR

它返回以下响应:

创建JPA存储库

在上述响应中,我们正在从数据库中检索值。

当我们在URI(EUR/to/INR)中传递货币时,查询将触发到数据库。要查看触发了哪个查询,我们可以在日志中看到该查询。

Hibernate: select exchangeva0_.id as id1_0_, exchangeva0_.conversion_multiple as conversi2_0_, exchangeva0_.currency_from as currency3_0_, exchangeva0_.port as port4_0_, exchangeva0_.currency_to as currency5_0_ from exchange_value exchangeva0_ where exchangeva0_.currency_from=? and exchangeva0_.currency_to=?

下一章:SpringCloud Feign REST客户端进行服务调用

在本节中,我们将从 Feign 流行的Spring Cloud组件之一开始。FeignFeign是由 Netflix 开发的声明性Web服务(HTTP客户端)。其目的是简化 ...