A Brief Guide To JPA Methods And Its Use In Spring Boot Framework

Posted By : Amit Patel | 30-Apr-2018

Here, I explain about JPA methods and It is working in Spring boot framework. JPA provides lots of methods , which we can use in spring boot framework and also perform operations like: accessing, persisting, and mapping data between classes and database. In spring boot, interface class extends the JpaRepository class, and we can perform CRUD operations through JPA repository.

 

Jpa Methods following these are:

 

save(Object o) : It saves data in relational database.

 

finAll() : It fetches all the records from database.

 

findOne(Integer id) : It retrieves an entity by its id.

 

delete(Integer id) : It delete the particular id record from database.

 

deleteAllInBatch() : Deletes all entities in a batch.

 

deleteAll() : Deletes all entities from relational database.

 

count() : Returns the number of entities available.

 

exists(Long id) :  Returns a boolean value, when an entity with the given id exists.

 

flush() : Flushes all pending changes to the database.

 

Custom method : We can also make custom method in Jpa repository. These are following :

 

deleteByCoinId(Integer coinId) : It delete the particular coinId record from database.

 

deleteByCoinName(String coinName) : It delete the particular CoinName record from database.

 

findByCoinId(Integer coinId) : It retrieves an field by its CoinId.

 

findByCoinIdAndCoinName() : It retrieves an field by its CoinId and coinName. 

 

In this example, we are creating domain class, service class, a controller class, and repository class. And the use of JPA methods. And also create a custom method in the repository.

 

We have an entity called Currency:

 

That is called model or domain class:

package com.trainingproject.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import com.trainingproject.enums.CoinType;

@Entity
@Table(name="currency")
public class Currency {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer coinId;
@Enumerated(EnumType.STRING)
private CoinType coinType;
@Column(unique = true)
@NotNull(message = "coinName not null")
private String coinName;
@Column(unique = true)
@NotNull(message = "symbol not null")
private String symbol;
@NotNull(message = "initialSupply not null")
private Integer initialSupply;
@NotNull(message = "price not null")
private Integer price;
private Integer fees;
private Integer profit;
private Long coinInINR;
private Currency() {
profit = 0;
coinInINR = 0l;
 }
public CoinType getCoinType() {
return coinType;
 }

public void setCoinType(CoinType coinType) {
this.coinType = coinType;
}
public Integer getCoinId() {
return coinId;
}
public void setCoinId(Integer coinId) {
this.coinId = coinId;
}
public String getCoinName() {
return coinName;
}
public void setCoinName(String coinName) {
this.coinName = coinName;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public Integer getInitialSupply() {
return initialSupply; 
}
public void setInitialSupply(Integer initialSupply) {
this.initialSupply = initialSupply;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getFees() {
return fees;
}
public void setFees(Integer fees) {
this.fees = fees;
}
public Integer getProfit() {
return profit;
}
public void setProfit(Integer profit) {
this.profit = profit;
}
public Long getCoinInINR() {
return coinInINR;
}
public void setCoinInINR(Long coinInINR) {
this.coinInINR = coinInINR;
}
}

And the interface class extend JpaRepository:

package com.trainingproject.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.trainingproject.domain.Currency;
@Repository
public interface CurrencyRepository extends JpaRepository<Currency, Integer> {
public Currency findByCoinIdAndCoinName(Integer coinId, String coinName);  // here create custom method in Repository.
public Currency findByCoinId(Integer coinId);  
public Currency deleteByCoinId(Integer coinId);
public Currency deleteByCoinIdAndCoinName(Integer coinId, String coinName);
}

And the service class having many methods:

package com.trainingproject.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.trainingproject.domain.Currency;
import com.trainingproject.repository.CurrencyRepository;
@Service
public class CurrencyService {
@Autowired
private CurrencyRepository currencyRepository;
Currency currencyobj;
Integer initialSupply; 
public Currency addCurrency(Currency currency) {
Currency addedCurrency = currencyRepository.save(currency);
return addedCurrency;
}

public List getAllCurrency() {
List list = new ArrayList();
currencyRepository.findAll()
.forEach(list::add);
return list;
}

public Optional getById(Integer coinId) {
return currencyRepository.findById(coinId);
}

public void updateCurrency(Currency currency) {
currencyobj = currencyRepository.findById(currency.getCoinId()).get();
initialSupply = currency.getInitialSupply();
initialSupply = initialSupply + currencyobj.getInitialSupply();
currency.setInitialSupply(initialSupply);
currencyRepository.save(currency);
}

public Currency findCurrency(Integer coinId, String coinName) {
return currencyRepository.findByCoinIdAndCoinName(coinId, coinName);
}

public void deleteCurrency(Integer coinId) {
currencyRepository.deleteById(coinId);
}

}

And the controller class , inside the controller class API's are created, in API's, call the service class method.

package com.trainingproject.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.trainingproject.domain.Currency;
import com.trainingproject.service.CurrencyService;
@RestController
public class CurrencyController {
@Autowired
private CurrencyService currencyService;
@RequestMapping(value = "/addcurrency",method = RequestMethod.POST)
public String func(@RequestBody Currency currency) {
Currency addedCurrency = currencyService.addCurrency(currency);
if(addedCurrency != null) {
return "success";
}
else
return "Failure";
}
@RequestMapping(value = "/getallcurrency",method = RequestMethod.GET)
public List getAllCurrency() {
return currencyService.getAllCurrency();
}
@RequestMapping(value = "/getcurrencybyid",method = RequestMethod.GET)
public Optional getById(@RequestParam("coinId") Integer coinId) {
return currencyService.getById(coinId);
}
@RequestMapping(value = "/updatecurrency",method = RequestMethod.POST)
public String updateCurrency(@RequestBody Currency currency) {
currencyService.updateCurrency(currency);
return "success";
}

@RequestMapping(value = "/deletecurrency",method = RequestMethod.GET)
public String deleteCurrency(@RequestParam("coinId") Integer coinId) {
currencyService.deleteCurrency(coinId);
return "success";
}

@RequestMapping(value = "/findcurrency", method = RequestMethod.Get)
public Currency findCurrency(@RequestParam("coinId") Integer coinId, @RequestParam("coinName") String coinName) {
return currencyService.findCurrency(coinId, coinName);
}

}

About Author

Author Image
Amit Patel

Amit Patel is having good knowledge of java,have expertise in hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..