Home > Back-end >  Java Spring boot: Repository & Service
Java Spring boot: Repository & Service

Time:10-14

please can you explain me shortly for what are responsible Repository class and Service class in Spring boot. As I know repo is for doing all the database operations and interacting with DB but somewhere I heard from videos that Service class talks to DB so I got confused and can't find any definition for them. Thank you very much for your time.

CodePudding user response:

Service class is where you perform your business logic which you do not want the user to view and repository class is where you perform database operations on an entity.

There is one more class called controller which is used to interact with web requests which are then forwarded to service methods and if there is need for data from database they send it forward to repository class.

Hope this explains. It is usually a design pattern for building production level applications Here is a short example

@Controller // Controller class
public class RequestController{
  @Autowired
  private ServiceClass service;
  @RequestMapping("")
  public string index(@Param("name") String name){
     return service.getString();
     }


@Service
public class ServiceClass{
 @Autowired
 private StuRepository repo;
 public String getString(String name){
   if(name.equals("Rahul")
    return repo.findName();
   else
     throw new Error("business logic performed here");
}


@Repository
public interface StuRepository extends JpaRepository<Model,Integer>{
String findName();
}
    

CodePudding user response:

@Service assigns Beans to handle logic

@Repository assigns Beans to take care of communicating with the DB

Architecture

  • Related