Spring Data

Configuring Spring Data JPA
  • Add Spring data JPA library to POM
  • Add database connectivity libraries to POM
    • For some databases like sqlite dialect is not available in Spring we may need to add it as separate library in this case.
CRUD Operations using Spring Data JPA
  • Add @Entity annotation to the entity classes.
    • These are the classes which map to tables in database
  • If you name a property in camel case then JPA will put an "_" in table name for example if you name property as courseId then JPA will look for column course_id in Table.
  • Generate getters and setters for the properties.
  • Next we need to create an interface which acts as a Repository for the entity for example CourseRepository etc.
    • This interface extends JpaRepository which is a Data Access Object or DAO.
    • DAO has built in methods for database interaction such as select insert and delete.
  • Crud Operations are performed using this DAO.
  • In our controller we inject the Database using auto-wired annotations.Next we can use methods like findAll(),delete(),save() from the Repository to perform CRUD operations on the database.
Entity Class
 package com.springimplant.cms.entities;  
 import java.math.BigInteger;  
 import javax.persistence.Entity;  
 import javax.persistence.Id;  
 import com.fasterxml.jackson.annotation.JsonIgnoreProperties;  
 @Entity  
 @JsonIgnoreProperties({"hibernateLazyInitializer","handler"})  
 public class Course {  
 @Id  
 private BigInteger courseid;  
 private String coursename;  
 private String author;  
 public Course() {  
 }  
 public BigInteger getCourseid() {  
      return courseid;  
 }  
 public void setCourseid(BigInteger courseid) {  
      this.courseid = courseid;  
 }  
 public String getCoursename() {  
      return coursename;  
 }  
 public void setCoursename(String coursename) {  
      this.coursename = coursename;  
 }  
 public String getAuthor() {  
      return author;  
 }  
 public void setAuthor(String author) {  
      this.author = author;  
 }  
 }  
Repository Class
 package com.springimplant.cms.repositories;  
 import java.math.BigInteger;  
 import org.springframework.data.jpa.repository.JpaRepository;  
 import com.springimplant.cms.entities.Course;  
 public interface CourseRepository extends JpaRepository<Course,BigInteger> {  
 }  
Controller
 package com.springimplant.cms.controller;  
 import java.math.BigInteger;  
 import java.util.Arrays;  
 import java.util.List;  
 import java.util.Optional;  
 import org.springframework.beans.factory.annotation.Autowired;  
 import org.springframework.web.bind.annotation.DeleteMapping;  
 import org.springframework.web.bind.annotation.GetMapping;  
 import org.springframework.web.bind.annotation.PathVariable;  
 import org.springframework.web.bind.annotation.PostMapping;  
 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.RestController;  
 import com.springimplant.cms.entities.Course;  
 import com.springimplant.cms.repositories.CourseRepository;  
 @RestController  
 public class CourseController {  
      @Autowired  
      private CourseRepository courseRepository;  
      @GetMapping("/")  
      public String courseApiHome()  
      {  
           return "Course API Home";  
      }  
      @GetMapping("/courses")  
      public List<Course> getCourses()  
      {  
           return courseRepository.findAll();  
      }  
      @GetMapping("/{id}")  
      public Course getSpecificCourse(@PathVariable("id") BigInteger id)  
      {  
           return courseRepository.getOne(id);  
      }  
      @GetMapping("/optional/{id}")  
      public Optional<Course> getSpecificOptionalCourse(@PathVariable("id") BigInteger id)  
      {  
           return courseRepository.findById(id);  
      }  
      @PostMapping(value="/courses")  
      public void saveCourse(@RequestBody Course course)  
      {  
           courseRepository.save(course);  
      }  
      @DeleteMapping(value="{id}")  
      public void deleteCourse(@PathVariable BigInteger id)  
      {  
           courseRepository.deleteById(id);  
      }  
 }  
  • We also need to set certain JPA properties in our properties file as shown below
    • These may vary depending upon your database we are using sqlite here.
 spring.jpa.database-platform=org.hibernate.dialect.SQLiteDialect  
 spring.jpa.hibernate.ddl-auto=none  
 spring.jpa.show-sql=true  
 spring.datasource.url=jdbc:sqlite:cms.db  
 spring.datasource.username=  
 spring.datasource.password=  
 spring.datasource.driver-class-name=org.sqlite.JDBC  

  • As we see above in our controller we use following functions to perform basic CRUD operations
    • Create Opeartion
      • save(project)
    • Read Operation
      • findById(id);
        • is used to fetch one record
        • returns object of type Optional
      • findAll()
        • used to  fetch all records
        • returns "List<object>" of records
      • getOne()
        • Returns the object directly
    • delete
      • deleteById(id)

No comments:

Post a Comment

Spring Boot

What is circular/cyclic dependency in spring boot? When two services are interdependent on each other, that is to start one service, we requ...