When updating an entity in spring mvc + jpa, the entity is updated in the database itself, but when trying to get the updated entity, the received data is not updated, when the same call is made inside the method after the update, the data comes updated.
An example on my code:
Controller (Spring MVC)
@PostMapping("/addBook")
public String putBooks(@ModelAttribute BookModel bookModel, HttpSession session, Model model ) {
bookService.addBook(bookModel);
UUID uuid = (UUID) session.getAttribute("UUID");
collectionsService.addCollectionsBook(bookService.getBookByTitle(bookModel.getTitle()), uuid);
System.out.println(bookCollectionsRepository.findAll());
return "/";
}
@GetMapping("/upd")
@ResponseBody
public String getMethodName( ) {
return bookCollectionsRepository.findAll().toString();
}
Tables
@Entity
@Table(name = "book")
@Data
public class BookModel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String authors;
private String img;
private String bookLink;
@ManyToMany(mappedBy = "books", fetch = FetchType.EAGER)
private Set<BookCollectionsModel> bookCollectionsModel = new HashSet<>();
public BookModel() {
}
}
@Entity
@Table(name = "book_collections")
@Data
public class BookCollectionsModel {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID uuid;
private String title;
private String author;
@CreationTimestamp
private Date created_at;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "books_collections",
joinColumns = @JoinColumn(name="book_collections_uuid"),
inverseJoinColumns = @JoinColumn(name="book_id")
)
@JsonManagedReference
private Set<BookModel> books = new HashSet<>();
}
Service method :
public void addCollectionsCategory(CategoryModel categoryModel, UUID uuid ){
BookCollectionsModel bookCollectionsModel = bookCollectionsRepository.findById(uuid).get();
bookCollectionsModel.getCategory().add(categoryModel);
bookCollectionsRepository.save(bookCollectionsModel);
}
Maybe the question is simple, but I could not find a solution or at least a direction to solve this problem.