Home > Back-end >  Multiple Spring JPA relationships between 2 entities
Multiple Spring JPA relationships between 2 entities

Time:01-23

I have 2 entities, one for a taskList and the other for users. The users can create tasks for themselves or their friends, so in the Tasks entity I have different columns referencing the User entity, one for createdBy another for createdFor and a last one for modifiedBy.
In the tasks entity I made the following @ManyToOne JPA relationships:

    @ManyToOne(optional = false)
    @JoinColumn(name = "created_by", nullable = false,
            referencedColumnName = "id")
    private User createdBy;

    @ManyToOne
    @JoinColumn(name = "created_for", nullable = false,
            referencedColumnName = "id")
    private User createdFor;

    @ManyToOne
    @JoinColumn(name = "modified_by", nullable = false,
            referencedColumnName = "id")
    private User modifiedBy;

But I am not sure how to do the linking in the Users side, I had the following @OneToMany relationship:

 @OneToMany(mappedBy = "createdFor", cascade = CascadeType.ALL)
    private List<Task> taskList;

But I am not sure how to proceed with the other relationships as I don't really need a taskList for the tasks that a user created, or what tasks did he modify.

CodePudding user response:

You do not need to map all things in an Entity , and also do not need to configure every relationships as bi-directional.

So if you really do not need to access the Tasks that are created and modified from a given User , just ignore them and do not map them in User.

It is perfectly valid to configure a relationship as unidirectional. Your existing codes should already work perfectly.

  •  Tags:  
  • Related