创建一个JPA存储库

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

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

public interface ExchangeValueRepository extends JpaRepository<ExchangeValue, Long>

步骤2: 打开CurrencyExchangeController.java文件并使用@Autowired注入ExchangeValueRepository

@Autowired
private ExchangeValueRepository repository;

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

ExchangeValue findByFromAndTo(String from, String to);

在上述语句中,ExchangeValue是预期的响应。我们要查找的是fromto两列。

如果我们想根据单个列查找数据,可以传递列名。例如:

ExchangeValue findByFrom(String from);

ExcahngeValueRepository.java

package cn.javatiku.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 cn.javatiku.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。它返回以下响应:

creating-a-jpa-repository.png

我们还可以尝试通过在URI中将货币USD更改为EUR来进行不同的转换。

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

它返回以下响应:

creating-a-jpa-repository-1.png

在上面的响应中,我们从数据库中检索了值。

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

Hibernate: select exchangeva0_.id as id1_0_, exchangeva0_.conversion_multiple as conversi2_0_, ex

标签: spring, Spring教程, spring cloud, spring cloud教程, spring cloud框架, spring cloud面试题, springcloud组件, springcloud微服务架构, springcloud入门教程, springcloud主件, spring cloud架构图