Create a JPA Repository

STEP 1: ExchangeValueRepository interface which extends JpaRepository


public interface ExchangeValueRepository extends JpaRepository<ExchangeValue, Long> {

//this method will give the implementation of given below method

//this is the magic of Spring data JPA,

//Once you provide method defination live given below you will get the implementation automaticaly

ExchangeValue findByFromAndTo(String from, String to);

}


STEP 2: Entity Class 

 @Entity

public class ExchangeValue {

@Id

private Long id;

@Column(name="currency_from")

private String from;

@Column(name="currency_to")

private String to;

@Column(name="conversion_multiple")

private BigDecimal conversionMultiple;

@Column(name="port")

private int port;

//Getter

//getter/setter for port

//default and param constructor

}



STEP 3: Controller Class


@RestController

public class CurrencyExchangeController {

@Autowired

private Environment environment;

@Autowired

private ExchangeValueRepository exchangeValueRepository;


@GetMapping("currency-exchange/from/{from}/to/{to}")

public ExchangeValue retrieveExchangeValue(@PathVariable String from, @PathVariable String to) {

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

exchangeValue.setPort(Integer.parseInt(environment.getProperty("local.server.port")));

return exchangeValue;

}

}

STEP 4: Application properties


spring.application.name=currency-exchange-service

server.port=8000


spring.jpa.show-sql=true

spring.h2.console.enabled=true


spring.datasource.url=jdbc:h2:mem:testdb;NON_KEYWORDS=USER

spring.h2.console.path=/h2-console

spring.jpa.defer-datasource-initialization=true

spring.data.jpa.repositories.bootstrap-mode=default


STEP 5: data.sql to intsert the default data



insert into exchange_value(id, currency_from, currency_to, conversion_multiple, port)

values(10001, 'USD', 'INR', 85,0);

insert into exchange_value(id, currency_from, currency_to, conversion_multiple, port)

values(10002, 'EUR', 'INR', 89, 0);

insert into exchange_value(id, currency_from, currency_to, conversion_multiple, port)

values(10003, 'AUD', 'INR', 53, 0);


Structur of the File


Database Data






by this code will get the exchange value From and to (your Database)


Query will be called from Code by given below url is

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


QUERY

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=?

Simplified Query


select * from exchange_value where currency_from='USD' and currency_to='INR'





Comments

Popular posts from this blog

Microservice with Java Spring Cloud

STEP 10 Configure Porfile for Limit service

STEP 9 Connect Limit service to Spring Cloud Config Server