Hibernate/JPA Bidirectional cascade saveOrUpdate

I am trying to have a many-to-many bidirectional relationship for 2 entities (News and Tag).

But when I try to saveOrUpdate the News (which has Set), somehow it always saves a new set of Tag even id is already populated in the Tag

Is it something wrong with my annotation?

News.java

    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    @Column(name = "NEWS_ID")
    public Long getId() {
        return id;
    }

    @ManyToMany(fetch = FetchType.LAZY,  cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @Cascade( org.hibernate.annotations.CascadeType.SAVE_UPDATE )
    @JoinTable(name = "NEWS_TAGS", joinColumns = @JoinColumn(name = "NEWS_ID"), inverseJoinColumns = @JoinColumn(name = "TAG_ID"))
    public Set<Tag> getTags() {
        return tags;
    }

Tag.java

    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    @Column(name = "TAG_ID")
    public Long getId() {
        return id;
    }

    private Collection<News> news;

    @JsonIgnore
    @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "tags")
    public Collection<News> getNews() {
        return news;
    }

NewsDAO

public void save(News news){
         this.hibernateSessionFactory.getCurrentSession().saveOrUpdate(news);
    }

What I want to do is when, I save "News", the related Set will be ignored if Tag exist, and will insert new if Tag isn't, is this possible?

Please advise

Answers


The problem is that your object (Tag) is not "connected". By that I mean hibernate is not aware of your object and, when you try to save News, hibernate will see your Tags as new Objects always. Try get the Tag object from db before save or update and use this object.


Need Your Help

Use SignalR to notify from wcf to JS

javascript jquery html5 wcf signalr

I want to use SignalR to recognize Jquery client on WCF service and board him messages even without a request. (Ie after the first request the client sends to the service, the service can to know h...

C# Microsoft.Office.Interop.Excel v15 slow

c# .net excel office-interop excel-interop

I am working on an application that needs to edit an excel file performing various actions like: