Home > Enterprise >  cant fetch elements from oneTomany relation in angular (backend spring boot)
cant fetch elements from oneTomany relation in angular (backend spring boot)

Time:10-24

I have 2 entities: Post and Comments and i wanna display all comments by post

Entity Post

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Post {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idPost;
    
    @CreationTimestamp
    private Date createdAt;
    private String content;
     
     @OneToMany(mappedBy = "post",fetch=FetchType.LAZY)
      @JsonIgnore
      private List<Comment> comments= new CopyOnWriteArrayList<>();


}

And entity Comment

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity

public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idComment;
    private String content;
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "postIdPost", referencedColumnName = "idPost")
    private Post post;
    
    
}

and this is in angular

import { User } from "./user";
import { Comment } from "./comment";
import { Like } from "./like";
export class Post {
    idPost!: number;
    user!:User;
    createdAt!:Date;
    content!:string;
    photo!:string;
    comments!: Comment[];
    likes:Like[]=[];
}

when i try to display comments by post it never displayed even when i try to access to comments length by {{posts.comments.length}} it shows nothing

<ng-container *ngFor="let p of posts">
            <div  >
              <div> p.content </div>
             .
             .
             .
 <ul  *ngFor="let com of p.comments   ">
  <p >{{com.content}}.</p>
</ul>

CodePudding user response:

You can try change the fetch strategy to fetch=FetchType.EAGER:

@OneToMany(mappedBy = "post", fetch=FetchType.EAGER)
@JsonIgnore
private List<Comment> comments= new CopyOnWriteArrayList<>();

CodePudding user response:

this is all post api GET enter image description here

and this is get allcomment api enter image description here

  • Related