On the front end, there is this code:
$("#add_button").click(function() {
console.log("The button has been pressed");
var genre = {
name: $("#genre_name").val(),
description: $("#genre_desc").val()
};
$.ajax({
type: "POST",
url: "/save_genre",
data: JSON.stringify(genre),
contentType: "application/json",
success: function(response) {
console.log("Genre successfully created:", response);
},
error: function(error) {
console.error("An error occurred while creating the genre:", error);
}
});
In it, by pressing a button, we read data from two forms, create an object, serialize it into JSON format and send a POST request to the server at the URL "/save_genre".
In turn, on the server side, we accept and write to the database:
@RestController
public class AddGenreRestController {
@Autowired
private GenreRepository GenreRepository;
@PostMapping("/save_genre")
public Genres addGenre(@RequestBody Genres genre) {
System.out.println("Genre = " + genre.GetName());
return GenreRepository.save(genre);
}
}
In response to the line: System.out.println("Genre = " + genre.GetName());
the value Genre = null
is printed to the console. A new record is created in the table, but the fields are also set to NULL
.
Why is this happening and how to fix it?
My "Generes" class:
@Entity
@Table(name="Genres")
public class Genres {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long ID;
private String name;
@Lob
@Column(columnDefinition = "text")
private String description;
public Genres() {
}
public Long GetID() { return ID; }
public void SetID(Long ID) { this.ID = ID; }
public String GetName() { return name; }
public void SetName(String name) { this.name = name; }
public String GetDescription () { return description; }
public void SetDescription(String description) { this.description = description; }
}
getter/setter names are not matching bean conventions, change to lowercase first letter or use Jackson annotations to mark it
public String getName() { return name; }
public void setName(String name) { this.name = name; }