package com.bjpowernode.hibernate;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.Session;
import junit.framework.TestCase;
public class Many2ManyTest extends TestCase {
public void testSave1() {
Session session = null;
try {
session = HibernateUtils.getSession();
session.beginTransaction();
User u1 = new User();
u1.setName("张三");
session.save(u1);
User u2 = new User();
u2.setName("李四");
session.save(u2);
User u3 = new User();
u3.setName("王五");
session.save(u3);
Role role = new Role();
role.setName("动力节点");
Set<User> users = new HashSet<User>();
users.add(u1);
users.add(u2);
users.add(u3);
role.setUsers(users);
session.save(role);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
} finally {
HibernateUtils.closeSession(session);
}
}
public void testLoad2() {
Session session = null;
try {
session = HibernateUtils.getSession();
session.beginTransaction();
Role role = (Role) session.load(Role.class, 1);
System.out.println(role.getName());
for (Iterator iter = role.getUsers().iterator(); iter.hasNext();) {
User user = (User) iter.next();
System.out.println(user.getName());
}
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
} finally {
HibernateUtils.closeSession(session);
}
}
}
4.多对多双向关联(用户对角色) 测试
最新推荐文章于 2024-06-27 17:31:05 发布