In which cases I need to use synchronize utilities methods


#1

In one-to-many relationship, It is suggested that I should create synchronize utilities methods like addPhone(), removePhone().
In my CRUD app, if i know the id of the owner-side entity, i can already use the enititymanager to add it like this:

public CommentDTO postComment(Integer threadID, String content, Integer userId) {
        User user = entityManager.getReference(User.class, userId);
        Thread thread = entityManager.getReference(Thread.class, threadID);
        Comment comment = new Comment(content, thread, user);
        commentRepository.save(comment); // or entityManager.persist(comment);
        return commentRepository.getCommentById(comment.getId());
    }

So if I already know ThreadID then I dont need to use synchronize utilities methods right?
Is there any difference if I do like this:

public CommentDTO postComment(Integer threadID, String content, Integer userId) {
       User user = entityManager.getReference(User.class, userId);
        Thread thread = entityManager.getReference(Thread.class, threadID);
        Comment comment = new Comment(content, user);
        thread.addComment(comment);
        entityManager.persist(thread);
        return commentRepository.getCommentById(comment.getId());
    }

#2

What’s the content of the non-default constructor of the Comment entity?

And why do you run the query when you already have a managed entity?


#3

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Comment extends BaseEntity {
    @NotBlank
    @Lob
    private String content;
    @ManyToOne(optional = false)
    private Thread thread;
    @ManyToOne(optional = false)
    private User author;
}


I rerun the query because I need to use Spring Data Projection (CommentDTO), I dont want to return full managed enitity to the client.


#4

Not using the utility methods is not guaranteed to work.

You don’t need to execute an extra DB query to get a projection. Use an adaptor or a tool like MapStruct for that.