简体   繁体   中英

Spring + Hibernate: saving and fetching data in many-to-many relation

I'm using Spring 3 + Hibernate and I have two entities (User, Address) related each other with the relation @ManyToMany. Every entity is mapped on a table ('user' and 'address') and the relation is defined by a linktable 'user_address' that maps user_id and address_id.

I have "method1" that saves 'User' when new address is added:

@Transactional
public void method1 (...) {
   /* do something*/
   user.getAddresses().add(address);
   session.save(user);
}

in another method2 I need to retrieve for a specific user, an address by the street:

@Transactional
public Address method2 (Long userId, String streetName) {
   String hql = "select distinct a from Address a " +
            "join a.users u " +
            "where u.id=:id and a.name=:name";
            Query query = session.createQuery(hql);
            query.setParameterList("id", userId);
            query.setParameterList("name", streetName);
            Address address = query.uniqueResult();
            return address;
}

The problem in this situation is when a new address is added via method1 it still may be in the cache when method2 is executed (so no address is returned) as method2 hits the database (that could be out-of-sync respect to cache). The only solution I found is adding a "flush" after method1 but I don't really like it. Do you know a better way to do it?

Calling a session.flush() manually in some methods is not a bad idea, at least for me.

There are alternatives:

  • Set Hibernate FlushMode to AUTO or ALWAYS (try AUTO first, should prevent stale results in queries, ALWAYS is to expensive to be useful)
  • Set PROPAGATION level to REQUIRES_NEW in Transactional annotation of method1: Will commit the method1 always, suspend current trasaction and createa new one to add the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM