//Class For Group
@Entity
@Table(name = "t_group")
public class Group {
private int id;//PK
private String name;
private Map<Integer, User> map = new HashMap<Integer, User>();
@OneToMany(mappedBy = "group", cascade = { CascadeType.ALL })
@MapKey(name="id")
public Map<Integer, User> getMap() {
return map;
}
//测试: // 存; User u1 = new User(); u1.setName("u1_name"); User u2 = new User(); u2.setName("u2_name"); Configuration cfg = new Configuration().configure(); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.getCurrentSession(); session.beginTransaction(); session.save(u1); session.save(u2); session.getTransaction().commit(); Session session2 = factory.getCurrentSession(); session2.beginTransaction(); Group group = new Group(); group.setName("u_group"); group.getMap().put(u1.getId(), u1); group.getMap().put(u2.getId(), u2); u1.setGroup(group); u2.setGroup(group); session2.save(group); session2.getTransaction().commit(); // 取; Session session3 = factory.getCurrentSession(); session3.beginTransaction(); Group _g = (Group) session3.load(Group.class, group.getId()); for (Map.Entry<Integer, User> entry : _g.getMap().entrySet()) { System.out.println(entry.getValue().getName()); } session3.getTransaction().commit();