Maifee Ul Asad
Maifee Ul Asad

Reputation: 4607

access many to many relation in spring

I have a class called Tag:

@Entity
@Table(name = "tags")
public class Tag {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @ManyToMany(fetch = FetchType.LAZY,
            cascade = {
                CascadeType.PERSIST,
                CascadeType.MERGE
            },
            mappedBy = "tags")
    private Set<Post> posts = new HashSet<>();

    ...
}

And a class called Post

@Entity
@Table(name = "posts")
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;


    @ManyToMany(fetch = FetchType.LAZY,
            cascade = {
                CascadeType.PERSIST,
                CascadeType.MERGE
            })
    @JoinTable(name = "post_tags",
            joinColumns = { @JoinColumn(name = "post_id") },
            inverseJoinColumns = { @JoinColumn(name = "tag_id") })
    private Set<Tag> tags = new HashSet<>();


        ...
}

It creates another table named post_tags.

How can I write a Controller to access that table as it is not similar a repository?

Is there more easy and convenient way to implement ManyToMany relationship ?

My pom.xml

Upvotes: 0

Views: 57

Answers (2)

dasunse
dasunse

Reputation: 3079

Use this way

@Entity
@Table(name = "tags")
public class Tag {

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

   @ManyToMany(cascade = CascadeType.ALL)
   @JoinTable(name = "post_tags",
        joinColumns = { @JoinColumn(name = "id") },
        inverseJoinColumns = { @JoinColumn(name = "post_id") })
   private Set<Post> posts = new HashSet<>();

...
}

@Entity
@Table(name = "posts")
public class Post {
   @Id
   @Column(name = "post_id")
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long postId;
    ...
}

Upvotes: 0

burna
burna

Reputation: 2962

You don't need to access that relation table manually. You can load load all Tag entities, and then load all the referenced Post entities.

The relation table is enterily managed by your ORM frameork.

But, if you still want to access the relation table, you can use native queries in your Spring Data JPA repository, e.g.

@Query(value="select post_id, tag_id from post_tags", nativeQuery=true)
List<PostTag> loadPostTags();

PostTag class is not a jpa-managed entity and must match the structue of the returned table:

public class PostTag {
 private long postId;
 private long tagId;
 // getter, setter
}

Upvotes: 1

Related Questions