Spring Data Jpa
Spring Data Jpa
1.CrudRepository:
2.JpaRepository:
Annotations:
Program:
application.properties file:
spring.application.name=StudentCRUD
spring.datasource.url=jdbc:mysql://localhost:3306/StudentDetails
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
Controller class:
package com.uniq.StudentCRUD.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;
import com.uniq.StudentCRUD.entity.Student;
import com.uniq.StudentCRUD.service.StudentService;
@RestController
@RequestMapping("/api")
public class StudentController {
@Autowired
StudentService service;
@PostMapping("/postdet")
public String postDetails(@RequestBody Student student) {
service.addDetails(student);
return "Add Successfully";
Service Class:
package com.uniq.StudentCRUD.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uniq.StudentCRUD.entity.Student;
import com.uniq.StudentCRUD.repository.StudentRepository;
@Service
public class StudentService {
@Autowired
StudentRepository repository;
repository.save(student);
Repository Layer:
package com.uniq.StudentCRUD.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.uniq.StudentCRUD.entity.Student;
@Repository
public interface StudentRepository extends CrudRepository<Student, Integer> {
}
Dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>