How to send back to an AJAX post an object with foreign entities

April 30, 2018, at 10:35 PM

I am developing a simple blogging website in Sping MVC. Currently I am trying to implement a form that allows to post a comment via AJAX post to a Spring MVC controller. The problem is that the success function defined in jquery is not invoked when I add an entity that has foreign entities defined in its model to the JSON response sent to the AJAX call. In this case I have Comment entity that has two foreign entities: User and Post.

I need to send back to the AJAX call the Comment entity created because I would like to insert the created object to the DOM through jquery.

These are my Comment, Post and User entities:

@Table(name = "COMMENTS")
public class Comment {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int commentid;
    private User author;
    private Post post;
    private List<Comment> replies;
    private Comment replyto;
    @NotEmpty(message="* Enter message for this comment.")
    @Column(name = "BODY")
    private String body;
    @Column(name = "PUBDATE")
    private LocalDateTime pubdate;
    // constructors
    // getters and setters
@Table(name = "POSTS")
public class Post {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int postid;
    @NotEmpty(message="* Enter a title for this post.")
    @Column(name = "TITLE")
    private String title;
    @Column(name = "SMALLTITLE")
    private String smalltitle;
    @NotEmpty(message="* Enter your post.")
    @Column(name = "POST")
    private String post;
    @Column(name = "SMALLPOST")
    private String smallpost;
    @Column(name = "PUBDATE")
    private LocalDateTime pubdate;
    private Blog ownerblog;
    private List<Comment> comments;
    @JoinTable(name = "POSTS_TAGS",
        joinColumns = @JoinColumn(name = "POSTID"),
        inverseJoinColumns = @JoinColumn(name = "TAGID")
    private List<Tag> tagslist;
   // constructors
   // getters and setters
@Table(name = "USERS", uniqueConstraints = {
        @UniqueConstraint(columnNames = {"USERNAME"}),
        @UniqueConstraint(columnNames = {"EMAIL"})
public class User {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int userid;
    private Blog blog;
    @NotEmpty(message="* Enter an original username.")
    @Column(name = "USERNAME")
    private String username;
    @Size(min = 6, message="* Enter a password with at least 6 characters.")
    @Column(name = "PASSWORD")
    private String password;
    @NotEmpty(message="* Enter a valid email address.")
    @Column(name = "EMAIL")
    private String email;
    @Column(name = "AVATAR")
    private String avatar;
    @NotEmpty(message="* Enter your first name.")
    @Column(name = "NAME")
    private String name;
    @NotEmpty(message="* Enter your last name.")
    @Column(name = "SURNAME")
    private String surname;
    @Column(name = "DESCRIPTION")
    private String description;
    @Column(name = "CREATION")
    private LocalDate creation;
    @Column(name = "ENABLED")
    private boolean enabled;
    private List<Comment> comments;
    private BCryptPasswordEncoder passwordEncoder;
    // constructors
    // getters and setters

This is my AJAX function:

$(document).ready(function() {
    /*  Submit form using Ajax */
    $('input[name=commentBtn]').click(function(e) {
        //Prevent default submission of form
        //Remove all errors
        $('textarea[class=comment]').css('border', '1px solid #ddd');
        var path = $(this).attr("path");
        var postbody = $('textarea[class=comment]').val();
            type: 'POST',
            url : path,
            data : {
                body: postbody
            success : function(res) {
                    $.each(res.errorMessages, function(key, value){
                        $('textarea[name='+key+']').after('<span class="error">'+value+'</span>');
                        $('textarea[name='+key+']').css('border', '1px solid red');

This is the controller that handle the AJAX POST:

public class CommentController {
    CommentRepository commentRepository;
    UserRepository userRepository;
    PostRepository postRepository;
    @RequestMapping(path     = { "/user/{userid}/blog/post/{postid}" }, 
                    method   = RequestMethod.POST, 
                    produces = { MediaType.APPLICATION_JSON_VALUE }
    public CommentJsonResponse commentPost(HttpServletRequest request,
            @PathVariable int postid,
            @RequestParam("body") String body) {
        CommentJsonResponse resp = new CommentJsonResponse();
        if(body.length() < 1) {
            resp.setErrorMessage("body", "* Enter a body for your comment.");
        else {
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("userSession");
            Post post = postRepository.findByPostid(postid);
            Comment comment = new Comment(body);
        return resp;

And finally this is the fragment of the JSP in which I have defined the form:

<c:set var = "path" value = "${pageContext.request.contextPath}/user/${post.ownerblog.owner.userid}/blog/post/${post.postid}"/>
<form method="POST" name="commentForm">
   <textarea class="comment" name="body"></textarea>
   <input name="commentBtn" type="submit" value="Submit Comment" path='<c:out value = "${path}"/>'>
Rent Charter Buses Company
How do I make an image move, but disappear in java?

How do I make an image move, but disappear in java?

just to preface, I am very new to javaSo expect dumb mistakes

What are the best benchmarking frameworks for parallel Java programs? [on hold]

What are the best benchmarking frameworks for parallel Java programs? [on hold]

I am particularly focusing on measuring speedup of a simple applicationIt will be very helpful if you can provide some references to good resources about benchmarking of parallel applications in general