Hibernate_Map_Mapping

//Class For Groupjava

@Entitysession

@Table(name = "t_group")app

public class Group {測試

private int id;//PKui

private String name;spa

private Map<Integer, User> map = new HashMap<Integer, User>();code

@OneToMany(mappedBy = "group", cascade = { CascadeType.ALL })對象

@MapKey(name="id")get

public Map<Integer, User> getMap() {it

return map;

}

gets/sets methods.....

//Class For User
public class User {

private int id;//PK
private String name;
private Group group;

// 對 User 對象相關聯的對象都自動級聯操做;
@ManyToOne(cascade = { CascadeType.ALL })

gets/sets methods...

//測試:
                // 存;
		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();
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息