在Hibernate多对多映射中需要以下方案的解决方案

时间:2018-11-16 12:03:56

标签: spring hibernate many-to-many

请考虑其中帖子标签表现出多对多关系的表。

多对多关系是使用名为post_tags的第三个表实现的,该表包含帖子的详细信息及其相关标签。

Post Model

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

    @NotNull
    @Size(max = 100)
    @Column(unique = true)
    private String title;

    @NotNull
    @Size(max = 250)
    private String description;

    @NotNull
    @Lob
    private String content;

    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "posted_at")
    private Date postedAt = new Date();

    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "last_updated_at")
    private Date lastUpdatedAt = new Date();


    @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<>();


    public Post() {

    }

    public Post(String title, String description, String content) {
        this.title = title;
        this.description = description;
        this.content = content;
    }

    // Getters and Setters (Omitted for brevity)
}

TAG Model

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

    @NotNull
    @Size(max = 100)
    @NaturalId
    private String name;

    @ManyToMany(fetch = FetchType.LAZY,
            cascade = {
                CascadeType.PERSIST,
                CascadeType.MERGE
            },
            mappedBy = "tags")
    private Set<Post> posts = new HashSet<>();

    public Tag() {

    }

    public Tag(String name) {
        this.name = name;
    }

    // Getters and Setters (Omitted for brevity)
}

问题是

我尝试使用现有标签。并仅在posts&posts_tags表上插入。

最初,我使用tagName获得标签。拥有Tag对象后,可以在Post对象中进行设置并保存。

 Post post = new Post("Hibernate Many to Many Example with Spring Boot",
                "Learn how to map a many to many relationship using hibernate",
                "Entire Post content with Sample code");

        // Create two tags
        Tag tag1 = tagService.getTag("Spring Boot");


        // Add tag references in the post
        post.getTags().add(tag1);

        postRepository.save(post);

如果我这样做,则post_tags表中不存在该条目。

标签存储库和标签服务:

@Repository
public interface TagRepository extends JpaRepository<Tag, Long> {

    @Query("select p from Tag p where p.name = :name")
    Tag findByName(@Param("name") String name);
}

@Override
public Tag findByName(String name) {
  return repository.findByName(name);
}

0 个答案:

没有答案