Wednesday, May 23, 2018

CRUD Operations using Spring boot JPA

Crud Operations using Spring Data JPA

import org.springframework.data.repository.CrudRepository;

public interface PersonDAO extends CrudRepository<Person, Long> {
}


Here PersonDAO Interface extends CrudRepository which contains crud operation methods and it accepts two generics,
Person - bean which you want to persist(Bean name)
Long - Type of primary key of the bean Person.(primary key is mandatory to persist)

Implementation

We dont really implement PersonDAO interface at all,Hibernate implements for use,we just use those method as shown below.

@Service
public class ServiceLayer {

@Autowired
private PersonDAO dao;

 public Person addPerson(Person person) {
  
  return dao.save(person);
 
 }
 public List getAllPerson() {
  
  return (List) dao.findAll();
 }
 
 public void deletePerson(int id) {
  
  dao.delete(id);
 }
}

If you observe closely we have just declared PersonDAO object, not intialized,Since it is annotated with @Autowired, Spring looks for the implementation available for that Interface and intializes for us,i.e DEPENDENCY INJECTION

Source code is available in next chapter
Share:

0 comments:

Post a Comment