package com.sw.test;
import java.util.List;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.sw.entity.Student;
import com.sw.entity.Teacher;
public class TestManyToMany {
private Session session;
private Transaction transaction;
@Before
public void before() {
Configuration configuration = new Configuration().configure();
SessionFactory factory = configuration.buildSessionFactory();
session = factory.openSession();
transaction = session.beginTransaction();
}
@Test
public void test() {
// 添加学生 添加老师
/*Teacher t = new Teacher("谢超");
Teacher t1 = new Teacher("黄玲");
Student s = new Student("张三");
Student s1=new Student("李四") ;
//互设
t.getStudents().add(s);
t.getStudents().add(s1);
t1.getStudents().add(s);
t1.getStudents().add(s1);
s.getTeachers().add(t);
s.getTeachers().add(t1);
s1.getTeachers().add(t);
s1.getTeachers().add(t1);
//保存
session.save(t);
session.save(t1);*/
//找到所有的老师 同时找到所有老师的学生
//List<Teacher> list=session.createQuery("from Teacher").list();
/*for (Teacher t : list) {
System.out.println(t.getTname());
Set<Student> teachers=t.getStudents();
for (Student s : teachers) {
System.out.println(s.getSname());
}
}*/
//找到一个老师找到他所有的学生
/*Teacher t=session.get(Teacher.class, 5);
System.out.println(t.getTname());*/
/*Set<Student> students=t.getStudents();
for (Student s : students) {
System.out.println(s.getSname());
}*/
//找到一个老师删除一个学生
/*Teacher t=session.get(Teacher.class, 5);
Student s=session.get(Student.class, 6);
//t.getStudents().remove(s);
session.delete(s);*/
//找到一个老师添加一个学生
/*Teacher t=session.get(Teacher.class, 5);
Student s=new Student("小强");
t.getStudents().add(s);
s.getTeachers().add(t);
session.save(s);*/
//找到一个学生找到一个老师 给这个学生
/*Teacher t=session.get(Teacher.class, 6);
Student s=session.get(Student.class, 7);
t.getStudents().add(s);
s.getTeachers().add(t);*/
/*Student s=session.get(Student.class, 7);
s.setSname("王二");
session.update(s);*/
}
@After
public void after() {
transaction.commit();
session.close();
}
}
manytomany
最新推荐文章于 2020-01-15 23:29:54 发布