加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

多对多关联xml配置测试

发布时间:2020-12-16 08:47:41 所属栏目:百科 来源:网络整理
导读:Student------Course: 1.Student.hbm.xml: hibernate-mapping package="com.buaa.hibernate.bean"class name="Student"id name="id" column="id"generator class="native"/generator/idproperty name="sname" column="stu_name"/propertyset name="courses"

Student<------>Course:

1.Student.hbm.xml:

<hibernate-mapping package="com.buaa.hibernate.bean">
	<class name="Student">
		<id name="id" column="id">
			<generator class="native"></generator>
		</id>
		<property name="sname" column="stu_name"></property>
		<set name="courses" table="stu_course" inverse="true">
			<key column="stu_id"></key>
			<many-to-many class="Course" column="course_id"></many-to-many>
		</set>
	</class>
</hibernate-mapping>

2.Course.hbm.xml:

<hibernate-mapping package="com.buaa.hibernate.bean">
	<class name="Course">
		<id name="id" column="id">
			<generator class="native"></generator>
		</id>
		<property name="cname" column="course_name"></property>
		<set name="students" table="stu_course">
			<key column="course_id"></key>
			<many-to-many class="Student" column="stu_id"></many-to-many>
		</set>
	</class>
</hibernate-mapping>

☆☆☆ 注意:inverse属性:只能有一个设置为true。也不能都不设置,否则会报异常(

1Duplicate entry'2-2' for key 'PRIMARY'

2Could notsynchronize database state with session

2ConstrainViolationException:Could not execute JDBC batch update;)


3.Test测试类:

public class Test extends TestCase {
	
	public void testMTM(){
		//MySessionFactory是自己写的一个类,获取session
		Session session = MySessionFactory.getSession(0);
		
		Student stu = new Student();
		stu.setSname("jack");
		Student stu2 = new Student();
		stu2.setSname("simon");
		Course course = new Course();
		course.setCname("English");
		Course course2 = new Course();
		course2.setCname("Math");
		
		Set<Course> courses = new HashSet<Course>();
		courses.add(course);
		courses.add(course2);
		Set<Student> students = new HashSet<Student>();
		students.add(stu);
		students.add(stu2);
		
		stu.setCourses(courses);
		stu2.setCourses(courses);
		course.setStudents(students);
		course2.setStudents(students);
		
		session.save(course);
		session.save(course2);
		session.save(stu);
		session.save(stu2);
		session.beginTransaction().commit();
		session.close();
		
	}
}

4.控制台输出:

Hibernate: insert into Course (course_name) values (?) Hibernate: insert into Course (course_name) values (?) Hibernate: insert into Student (stu_name) values (?) Hibernate: insert into Student (stu_name) values (?) Hibernate: insert into stu_course (course_id,stu_id) values (?,?) Hibernate: insert into stu_course (course_id,?)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读