Milad
Milad

Reputation: 77

How To Make Relations Between Two Entities From Different Microservices In Spring Boot?

I am trying to make a simple Spring Boot web app using Microservice Architecture.

I have two microservices with entities as defined below:

Microservice 1 :

@Entity
public class Article {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    private String Content;

}

and

Microservice 2 :

@Entity
public class Tag {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
}

Now I want to have a Many To Many relation between these two entities in my Gateway.

I had tried to use feign client as below:

Gateway :

@FeignClient(value = "article-service")
public interface ArticleClient {

    @RequestMapping(value = "/articles/", method = RequestMethod.GET)
    Set<Article> getArticleById(@RequestParam("id") Long id);

}

@FeignClient(value = "tag-service")
public interface TagClient {

    @RequestMapping(value = "/tags/", method = RequestMethod.GET)
    Tag getTagById(@RequestParam("id") Long id);

}

And defined Article and Tag entities in my Gateway like this:

Gateway :

@JsonIgnoreProperties(ignoreUnknown = true)
public class Entry {

    private Long id;

    private String title;

    private String Content;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "article_tag",
        joinColumns = @JoinColumn(name = "article_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "tag_id",
                referencedColumnName = "id"))
    private Set<Tag> tags;
}


@JsonIgnoreProperties(ignoreUnknown = true)
public class Tag {
    private Long id;

    private String title;

    @ManyToMany(mappedBy = "tags")
    private Set<Article> articles;
}

I have a table named article_tag in my database (Postgres).

Now how can I define my repositories in the Gateway? How to write getArticlesByTagId() or getTagsByArticleId() functions? I did whatever I could to make this relation work but I think they are not going to get along with each other :)

Upvotes: 5

Views: 6556

Answers (1)

akuma8
akuma8

Reputation: 4691

It just impossible what you want, you have 2 differents applications, each entity has its own life in its context. Imagine the case where a service is down, how would you do?

If a microservice is closely linked to another one, you should revise your architecture.

To solve this kind of problem, add an identifier in each entity to identify which Tag belongs to an Entry and vice-versa, you can request your data using those identifiers.

Upvotes: 3

Related Questions