Insert using Many to Many Annotation does not work

Asked

Viewed 41 times

0

Hello,

I have a Many to Many relationship between TEAM and NEWS. I am trying to create a method to insert a "NEWS". I am using Hibernate with Annotation to map the classes.

The Insert works and persists correctly in the NEWS table, but in the NEWS_TEAM table it does not insert. No error is shown...only it does not insert.

I did the test and added the record in the NEWS_TEAM table manually, direct in the database, and performed a simple listing using criteria, and it worked, but the Insert did not work.

Someone’s been through something like this?

Follows the method Newsbusinessimpl class Insert:

public void create(News news) {
    Session session = null;
    Transaction tx = null;
    try {
        session = PoliGenericDAO.getSessionFactory().openSession();
        tx = session.beginTransaction();
        session.save(news);
        session.flush();
        tx.commit();
    } catch (Exception e) {
        System.out.println("create.News.Error: " + e);
    }finally {
        session.close();
    }
}

Follow the Entity NEWS:

...

@LazyCollection(LazyCollectionOption.FALSE)
@ManyToMany(mappedBy = "newsList", targetEntity = Team.class, cascade = CascadeType.DETACH)
private Set<Team> teamList;

Follow the Entiadade TEAM:

@ManyToMany(cascade={CascadeType.MERGE,CascadeType.PERSIST},  fetch = FetchType.EAGER)
@JoinTable(name = "NEWS_TEAM", joinColumns = { @JoinColumn(name = "TEAM_ID") }, inverseJoinColumns = { @JoinColumn(name = "NEWS_ID") })
private Set<News> newsList;

1 answer

0


If the Team type objects are already in the database, you should add them to the News object list and only after that you can add them to the database, for example:

news.getTeams().addAll(lista de objetos do tipo Team);
session.save(news);

Also, for each Team type object that is in the News list you should also add it in the Team list, the final code would be like this:

news.getTeams().addAll(lista de objetos do tipo Team);
news = session.save(news);//Retorna o obj com ID
for(Team objTeam : news.getTeams()){
   objTeam.getNews().add(news);
   session2.save(objTeam);
}
  • Hello Fabio.. thanks for the reply...but the error was not what you said...I was already doing that way...sorry if I did not put the code. The mistake in my case was that I changed the notations from Many to Many. The "dominant entity" in the relation was wrong. Vlw helps!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.