Writing APIs in springboot is pretty straightforward and has in construct assist, I’d not offer you steps to obtain or arrange the atmosphere for spring boot slightly you should utilize some on-line sources to configure your growth atmosphere.
I’ve used Eclipse with h2 Database assist however you should utilize PostgreSQL it’s pretty straightforward to arrange.
Prerequisite :
1 Setup Spring boot starter App utilizing https://begin.spring.io/ .
2. Obtain and arrange the Database or use h2 db that don’t any want further configuration.
3. Set up Eclipse.
Design The Schema :
For the given JSON let’s create a Desk or Entity in Sprinboot, as we all know that Entities in Springboot are class representations of Database tables.
@Entity
public class StockTrade {@Id
@GeneratedValue(technique = GenerationType.AUTO)
personal Integer id;
personal String kind;
personal Integer userId;
personal String image;
personal Integer shares;
personal Integer worth;
personal Lengthy timestamp;
public StockTrade() {
}
}
// Getter and Setters
I’ll create a JPARepository similar to this desk to retrieve the rows from the Desk
@Repository
public interface StockTradeRepository extends JpaRepository {
}
Service
Now I’ll create a Service class that shall be chargeable for accessing this Desk and getting the databases upon the necessities :
bundle com.hackerrank.stocktrades.service;import java.util.ArrayList;
import java.util.Checklist;
import java.util.stream.Collectors;
import org.modelmapper.ModelMapper;
import org.springframework.beans.manufacturing facility.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hackerrank.stocktrades.mannequin.StockTrade;
import com.hackerrank.stocktrades.mannequin.StockTradeDTO;
import com.hackerrank.stocktrades.repository.StockTradeRepository;
@Service
public class TradeService {
@Autowired
StockTradeRepository stockRepository;
personal static ModelMapper modelMapper = new ModelMapper();
public StockTradeDTO createNewStock(StockTradeDTO stockTradeDto) throws java.textual content.ParseException {
stockTradeDto.setId(null);
StockTrade stockEntity = modelMapper.map(stockTradeDto, StockTrade.class);
stockEntity = stockRepository.save(stockEntity);
return getStockDto(stockEntity);
}
public Checklist getStock() {
return convertEntityToDTO(stockRepository.findAll());
}
public Checklist filterBy(String kind, Integer userId) {
Checklist trades = stockRepository.findAll();
if (kind != null && userId != null) {
// Filter trades by each kind and userId
trades = trades.stream().filter(t -> t.getType().equals(kind) && t.getUserId() == userId)
.accumulate(Collectors.toList());
} else if (kind != null) {
// Filter trades by kind
trades = trades.stream().filter(t -> t.getType().equals(kind)).accumulate(Collectors.toList());
} else if (userId != null) {
// Filter trades by userId
trades = trades.stream().filter(t -> t.getUserId() == userId).accumulate(Collectors.toList());
}
return convertEntityToDTO(trades);
}
public StockTradeDTO getStockById(int id) {
if(stockRepository.existsById(id)) {
StockTrade stockTradeEntity = stockRepository.findById(id).get();
return modelMapper.map(stockTradeEntity, StockTradeDTO.class);
}
else {
return null;
}
}
personal Checklist convertEntityToDTO(Checklist checklist) {
Checklist dtoList = new ArrayList();
for (StockTrade inventory : checklist) {
dtoList.add(modelMapper.map(inventory, StockTradeDTO.class));
}
return dtoList;
}
personal StockTradeDTO getStockDto(StockTrade stockEntity) {
StockTradeDTO w = modelMapper.map(stockEntity, StockTradeDTO.class);
return w;
}
}
In Service Class, I’ve strategies to Create Inventory, Get Inventory by Id, and filter Inventory by Sort :
1. createNewStock(StockTradeDTO stockTradeDto)
2. getStock()
3. filterBy(String kind, Integer userId)
4. getStockById(int id)
Controller :
Let’s name these service strategies from the Controller and expose them :
StockTradeRestController.Java
@RestController
@RequestMapping(path = "/trades")
public class StockTradeRestController {@Autowired
TradeService tradeService;
}
POST request to /trades
:
Add createStock Methodology within the controller , It can create an new Inventory within the Database.
@PostMapping
public ResponseEntity> createStock(@RequestBody StockTradeDTO climate) throws ParseException {
StockTradeDTO w = tradeService.createNewStock(climate);
return new ResponseEntity<>(w, HttpStatus.CREATED);
}
GET request to /trades
:
GET request to /trades/
:
Add getAllTrades() and getWeatherById(@PathVariable int id) within the controller class, It can return all Shares from the Database.
@GetMapping()
public ResponseEntity> getAllTrades() {return ResponseEntity.okay(tradeService.getStock());
}
@GetMapping("/{id}")
public ResponseEntity> getWeatherById(@PathVariable int id) {
StockTradeDTO commerce = tradeService.getStockById(id);
if (commerce != null) {
return new ResponseEntity<>(commerce, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
Lets add Filter by kind and StockId :
@GetMapping("/")
public ResponseEntity> getFilters(@RequestParam(required = false) String kind,
@RequestParam(required = false) Integer userId) {Checklist weathers = new ArrayList<>();
if (kind != null || userId != null) {
weathers = tradeService.filterBy(kind, userId);
return ResponseEntity.okay(weathers);
}
return ResponseEntity.okay(tradeService.getStock());
}
Within the final how my pom.xml looksalike, add these depencies in :
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-test
check
com.h2database
h2
1.4.197
org.modelmapper
modelmapper
2.4.5
commons-fileupload
commons-fileupload
1.4
Add these in software.properties to configure the Database:
server.port=8080
server.tackle=0.0.0.0
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
I hope it’s going to allow you to to resolve the Hacker Rank Backend function evaluation, Many of the questions are virtually comparable.
Comply with me on LinkedIn .