Spring Cloud创建一个JPA存储库示例

在上一节中, 我们创建了一个表内存数据库, 并看到正确填充了所有数据。在本节中, 我们将创建一个存储库, 该存储库返回服务的响应。
步骤1:创建一个名称为ExchangeValueRepository的接口, 并扩展JpaRepository类。我们必须传递两个参数:它管理的实体的类型和Id字段的类型。

public interface ExchangeValueRepository extends JpaRepository< ExchangeValue, Long>

步骤2:打开CurrencyExchageController.java文件, 并自动连接ExchageValueRepository。
@Autowiredprivate ExchangeValueRepository repository;

步骤3:在ExcahngeValueRepository.java文件中创建查询方法。
ExchangeValue findByFromAndTo(String from, String to);

在上面的语句中, ExchangeValue是预期的响应。我们必须找到来自和到的两列。
如果要基于单列查找数据, 则可以传递列名。例如:
ExchangeValue findByFrom (String from);

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

步骤4:在CurrencyExchangeController.java中, 使用以下语句:
ExchangeValue exchangeValue=http://www.srcmini.com/repository.findByFromAndTo(from, to);

而不是使用以下语句:
ExchangeValue exchangeValue=http://www.srcmini.com/new ExchangeValue(1000L, from, to, BigDecimal.valueOf(65));

CurrencyExchangeController.java
package com.srcmini.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 {@Autowiredprivate Environment environment; @Autowiredprivate ExchangeValueRepository repository; @GetMapping("/currency-exchange/from/{from}/to/{to}")//where {from} and {to} are path variablepublic ExchangeValue retrieveExchangeValue(@PathVariable String from, @PathVariable String to)//from map to USD and to map to INR{ExchangeValue exchangeValue = http://www.srcmini.com/repository.findByFromAndTo(from, to); //setting the portexchangeValue.setPort(Integer.parseInt(environment.getProperty("local.server.port"))); return exchangeValue; }}

步骤5:重新启动应用程序以获取更改。打开浏览器, 然后输入URI http:// localhost:8000 / currency-exchange / from / USD / to / INR。它返回以下响应:
Spring Cloud创建一个JPA存储库示例

文章图片
我们也可以尝试通过将URI中的货币USD更改为EUR来进行其他转换。
http:// localhost:8000 / currency-exchange / from / EUR / to / INR。
它返回以下响应:
Spring Cloud创建一个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=?

【Spring Cloud创建一个JPA存储库示例】点击这里下载货币兑换服务

    推荐阅读