Ra Ven
Ra Ven

Reputation: 25

Broken relationships in Spring

I have three entities:

@EqualsAndHashCode(callSuper = true)
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "author")
public class Author extends IdEntity {

    private String firstName;
    private String lastName;

    @Email(message = "Provide a valid email")
    @NotEmpty(message = "Email cannot be empty")
    private String email;

    private String userName;

    @Length(min = 5, message = "XD")
    @NotEmpty(message = "Password cannot be empty")
    private String password;
    private String profilePic;
    private String description;
    @CreationTimestamp
    private Date createdAt;

    @JsonManagedReference
    @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "author")
    @Transient
    private Set<Post> posts;

    public Post getPostById(Long postId) {
        for (Post post: posts)
            if (post.getId().equals(postId))
                return post;
            return null;
    }

    public Author(String firstName, String lastName, @Email(message = "Provide a valid email") @NotEmpty(message = "Email cannot be empty") String email, String userName, @Length(min = 5, message = "XD") @NotEmpty(message = "Password cannot be empty") String password, String profilePic, String description, Date createdAt) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.userName = userName;
        this.password = password;
        this.profilePic = profilePic;
        this.description = description;
        this.createdAt = createdAt;
    }

}

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "comment")
public class Comment extends IdEntity {

    private String content;
    @CreationTimestamp
    private Date createdAt;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(
            name = "author_id",
            nullable = false,
            foreignKey = @ForeignKey(
                    name = "fk_authors_id"
            ))
    @ToString.Exclude
    @NotNull
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    private Author author;

    @JsonBackReference
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(
            name = "post_id",
            nullable = false,
            foreignKey = @ForeignKey(
                    name = "fk_posts_id"
            ))
    @ToString.Exclude
    @NotNull
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    private Post post;

}


@EqualsAndHashCode(callSuper = true)
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "post")
public class Post extends IdEntity {

    @Length(min = 5, message = "Your title must have at least 5 characters")
    @NotEmpty(message = "Please provide title")
    private String title;
    private String content;
    @CreationTimestamp
    private LocalDateTime createdAt;
    //private LocalDateTime updatedAt;
    private int likes;
    private int views;

    @JsonBackReference
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(
            name = "author_id",
            nullable = false,
            foreignKey = @ForeignKey(
                    name = "fk_authors_id"
            ))
    @ToString.Exclude
    @NotNull
    private Author author;

    @JsonManagedReference
    @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "post", cascade = CascadeType.ALL)
    @Transient
    private Collection<Comment> comments;


    //Section, Category, Tags, featured, published
    //Add other reactions

}

Every time I'm trying to add Post. It should be added to Post table and automatically to Author table, but It's nothing happen. Instead of bidirectional mapping, it looks rather like OneToMany mapping. I have no idea how can I fix it. Here's source code of broken module : github.com/Wardenclyffee/Wardenclyffe/tree/comment-posting/server

Upvotes: 1

Views: 117

Answers (1)

Vetemi
Vetemi

Reputation: 851

If I understand you correctly you want to add authors when adding posts. In that case you'd need to tell that Hibernate by specifying the cascading type:

@JsonBackReference
@ManyToOne(
        fetch = FetchType.LAZY, 
        optional = false,
        cascade = CascadeType.PERSIST)
@JoinColumn(
        name = "author_id",
        nullable = false,
        foreignKey = @ForeignKey(
                name = "fk_authors_id"
        ))
@ToString.Exclude
@NotNull
private Author author;

For more information about cascading types in Hibernate check out the web. There are plenty resources.

Also, it looks wrong to set @Transient Annotation to the Posts-Set in Author Entity. I don't know what happens but I'd remove that because transient fields are for fields which should not be stored in the database but in this case Hibernate will properly handle the association.

Upvotes: 2

Related Questions