Home > Back-end >  How should I map my one table to another using JPARepositoy?
How should I map my one table to another using JPARepositoy?

Time:01-29

I have a table schema like this. Notification can be of 2 types : twitter or fb

For each notification, there will be 1 row in notification table and 1 in either twitter_post/ fb_post.

Each table have auto sequence id generator.

FBPost and TwitterPost is mapped via notification_id (PK)

enter image description here

I have created entity class like this:

@Entity
@Table(name = "notification")
public class Notification {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "not_id_sequence")
    private String id;

    @Column(name = "description")
    private String description;

    @OneToOne(mappedBy = "notification")
    private FBPost fbPost;

    @OneToOne(mappedBy = "notification")
    private TwitterPost twitterPost;    
}


@Entity
@Table(name = "fb_post")
public class FBPost {    
    @Id
    @Column(name = "post_id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "post_fid_sequence")
    private Long postId;

    @Column(name = "post_content")
    private String postContent;
    
    @OneToOne
    private Notification notification;    
}


@Entity
@Table(name = "twitter_post")
public class TwitterPost {

    @Id
    @Column(name = "post_id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "post_tid_sequence")
    private Long postId;

    @Column(name = "post_content")
    private String postContent;
    
    @OneToOne
    private Notification notification;

}

I am using JpaRepository to save into the database. But not getting any row into fb_post or twitter_post table.

Am i doing it wrong in entity class.

CodePudding user response:

Try adding @JoinColumn(name = "notification_id", referencedColumnName = "notification_id") below @oneToOne in TwitterPost and FBPost class for the notification variable

CodePudding user response:

Looks like you are missing cascade. Try to add cascade = CascadeType.ALL into @OneToOne of the parent entity - Notification:

@Entity
@Table(name = "notification")
public class Notification {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "not_id_sequence")
    private String id;

    @Column(name = "description")
    private String description;

    @OneToOne(mappedBy = "notification", cascade = CascadeType.ALL)
    private FBPost fbPost;

    @OneToOne(mappedBy = "notification", cascade = CascadeType.ALL)
    private TwitterPost twitterPost;    
}

For more information I would recommend to read hot to map one-to-one relationship.

  •  Tags:  
  • Related