A quick tutorial for middleware products

Monday, April 8, 2019

On April 08, 2019 by Kamlesh   No comments
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 

0 comments:

Post a Comment