Hibernate ManyToMany and deletes

Some fun times with hibernate indeed.  Of course, I have to figure out this myself since the hibernate forums are the most useless forums in existence.

Here's the scenario, and how I fixed it.

I have 2 domain objects in a bi-directional ManyToMany relationship (Groups and Roles).  Nothing new here.

The problem happens if you add/remove any associations AFTER the cache has been initialized.  

  1. Create a Group and load it into your hibernate session. The Group.getRoles() is currently empty and the cache is initalized.
  2. Create a Role and load it into your hibernate session
  3. Assocation the Role to a group, role.getGroups().add(group) and group.getRoles().add(role)
  4. Load the Group from hibernate again.  Nothing is in the Group.getRoles() collection.

Everything works fine if you disable the Cache on the ManyToMany, but I don't want to do that!

The problem I had related to being able to delete these things, so what I did was if I want to delete a Group, I would call a special "finder" that would load the Group and not use the cache.  Here is the method that I used, this worked for me.

 

    public Group findGroupByIdNoCache(final Long groupId) {

        Group group = (Group) getHibernateTemplate().execute(
                new HibernateCallback() {
                    public Object doInHibernate(Session session)
                            throws HibernateException, SQLException {
                        session.setCacheMode(CacheMode.REFRESH);
                        Group group = (Group) session
                                .load(Group.class, groupId);

                        Hibernate.initialize(groupId);

                       Hibernate.initialize(group.getRoles());

                        return group;

                    }
                });

        return group;
    }

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options