Spring MVC和Thymeleaf-POST请求后丢失的子实体的集合

时间:2019-05-06 22:07:04

标签: hibernate spring-mvc thymeleaf

我正在使用Spring MVC,Thymeleaf和Hibernate来构建基本的CRUD应用程序。我正在建立具有多对多关系的两个实体Author和Book。 Author使用HashSet来存储Books,而Book使用HashSet来存储Authors。

尝试更新作者时遇到问题。当浏览器使用“作者”的当前数据加载“更新”表单时,我已经验证了“作者的书”数据是完整的。但是,当我为该Author提交POST请求时,Author.books变量会以某种方式丢失其Book数据。此时将Author保存到数据库将使关系丢失永久化。

我尝试了多种方法来建立多对多关系,但无济于事。

作者实体

GIT_SSH_COMMAND="ssh -i $SSH_KEY" git push origin feature/Jenkinsfile

图书实体

@Entity
@Table(name="author")
public class Author {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="middle_name")
    private String middleName;

    @Column(name="last_name")
    private String lastName;

    @ManyToMany(fetch=FetchType.LAZY,
                cascade={CascadeType.MERGE, CascadeType.PERSIST})
    @JoinTable(
    name="book_author",
    joinColumns=@JoinColumn(name="author_id"),
    inverseJoinColumns=@JoinColumn(name="book_id")
            )
    @OrderBy("title")
    private Set<Book> books = new HashSet<>();

    // constructor, getters, and setters

控制器

@Entity
@Table(name="book")
public class Book {

    // Some fields belonging to Book

    @ManyToMany(fetch=FetchType.LAZY,
                cascade={CascadeType.MERGE, CascadeType.PERSIST},
                mappedBy="books")   
    @OrderBy("lastName")
    private Set<Author> authors = new HashSet<>();

    // constructor, getters, and setters

作者表单HTML

@Controller
@RequestMapping("/authors")
public class AuthorController {

    private AuthorService authorService;

    @Autowired
    public AuthorController(AuthorService authorService) {
        this.authorService = authorService;
    }

    @GetMapping("/update")
    public String showFormForUpdate(@RequestParam("authorID") int authorID, 
                                Model model) {

        Author author = authorService.findByID(authorID);

        model.addAttribute("author", author);
        model.addAttribute("action", "/authors/save");

        return "/authors/author-form";
    }

    @PostMapping("/save")
        public String saveAuthor(@ModelAttribute("author") Author author) {
        // Book data is lost by this point

        authorService.save(author);

    return "redirect:/authors/all";
    }
}

0 个答案:

没有答案