Thursday, 1 March 2018

How to use JPA and Repository with Spring application ?


Let 's suppose, we need to serve data using DB on HTTP URLs.
For this example, we are using an in-memory DB (like, H2)
  • Provide dependencies of Data JPA and H2 DB in maven config
  • Define DB properties in application.properties
  • Create a Repository for data entity by extending CrudRepository.
  • Inside controller, expose different APIs, inject this repository and call its CRUD methods

1. Add dependencies of data-jpa and h2 DB along with data-rest for exposing APIs.
        <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>



2. Define DB properties in application.properties
spring.datasource.url=jdbc:h2:file:~/training;DB_CLOSE_ON_EXIT=TRUE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.show-sql=true



3. Create a POJO - Data model
@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)

    private Long id;

    @NotNull
    @Size(min = 2, max = 10)
    @Column(length=60, updatable=false)

    private String name;
       
    private double salary;


    // Getters and setters
       
    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
    }

 }


4. Create repository
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
    // Optional : Customized methods

    // List<Employee> findByName(String name);
 
    // @Query("SELECT e from Employee e where e.salary=:salary")
    // List<Employee> fetchData(@Param("Salary") double salary);

}





5. Create controller and methods (exposed APIs) and access the repository
@Component
@RequestMapping("emp")

public class EmpController {

    @Resource
    private EmployeeRepository employeeRepository;
   
    @GetMapping
    public ResponseEntity<List<Employee>> getAllEmp() {
        return ResponseEntity.ok((List<Employee>) employeeRepository.findAll());
    }
   
    @GetMapping("{id}")
    public ResponseEntity<Employee> emp(@PathVariable long id) {
        return ResponseEntity.ok(employeeRepository.findOne(id));
    }
   
    @PostMapping
    public ResponseEntity<Employee> emp(@RequestBody Employee emp) {
        return ResponseEntity.ok(employeeRepository.save(emp));
    }
   
    @PutMapping
    public ResponseEntity<Employee> emp(@PathVariable long id, @Valid @RequestBody Employee emp) {
        return ResponseEntity.ok(employeeRepository.save(emp));
    }
}


 
6. Start the application and Test using Postman / RESTClient :
1. GET http://localhost:8080/emp

2. POST http://localhost:8080/emp
Request Body = { "name" : "shaan", "salary" : 12 }
Header = Content-Type : application/json


No comments:

Post a Comment

Note: only a member of this blog may post a comment.