Home > Back-end >  JPA is not saving data
JPA is not saving data

Time:12-27

Im trying to save data to the database, but instead of it JPA is saving null to the database, I am usually doing it with dto, but since it s a very small project, I want to do it without it

Entity

  @Setter
@Getter
@Entity
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String surname;
    private String department;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "STUDENT_COURSE_TABLE",
    joinColumns = {
            @JoinColumn(name="student_id",referencedColumnName = "id")
    }, inverseJoinColumns = {
            @JoinColumn(name = "couse_id",referencedColumnName = "id")
    })
    @JsonManagedReference
    private Set<Course> courses;
}

DAO

    @Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}

Controller

@RestController
@RequestMapping("/api")
public class StudentCourseController {

    private final StudentRepository studentRepository;

    private final CourseRepository courseRepository;

    public StudentCourseController(StudentRepository studentRepository,
                                   CourseRepository courseRepository) {
        this.studentRepository = studentRepository;
        this.courseRepository = courseRepository;
    }

    @PostMapping
    public Student addStudent (Student student){
        return studentRepository.save(student);
    }



}

and in my application.properties

spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialec

t

CodePudding user response:

Make sure is deserialization correct in controller method "addStudent" - If You want to pass Student entity in request body, add annotation @RequestBody to method parameter like:

 @PostMapping
    public Student addStudent (@RequestBody Student student){
        return studentRepository.save(student);
    }

If You do not do that - there is possibility to null/empty parameter, what can lead to saving nulls into db.

By the way:

  • Consider using DTO or Request classes to pass entity in/out your REST application - it will help you avoid circular reference in future and problems with de/serialization your entity.
  • Consider using ResponseEntity instead of returning object to output - method with ResponseEntity should be like:
   @PostMapping
   public ResponseEntity<Student> addStudent (@RequestBody Student 
   student){
       return ResponseEntity.ok(studentRepository.save(student));
   }
  • Related