hibernate框架的表的多对多小练习

 1.在64位的Java中新建一个Dynamic web java 项目:(64位Java的下载地址:https://www.eclipse.org/downloads/download.php?file=/oomph/epp/2019-03/R/eclipse-inst-win64.exe

2.在项目的WebContent-WEBINF-lib目录下的放入相应包:(包的下载地址:https://download.csdn.net/download/zongzhe520/11048766

3.在src中写如下代码:

(1):创建包com.hiber.pojo在包中新建Course类和Student类和.xml文件(Course.hbm.xml文件和Student.hbm.xml文件)

代码如下:

【1】Course类:

package com.hiber.pojo;

import java.util.HashSet;
import java.util.Set;

public class Course {
    int id;
    String name;
    Set<Student> students = new HashSet();
    
	public Set<Student> getStudents() {
		return students;
	}
	public void setStudents(Set<Student> students) {
		this.students = students;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
    
}

【2】Student类:

package com.hiber.pojo;

import java.util.HashSet;
import java.util.Set;

public class Student {
    int id;
    String name;
    Set<Course> courses =new HashSet();
	
    public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Set<Course> getCourses() {
		return courses;
	}
	public void setCourses(Set<Course> courses) {
		this.courses = courses;
	}
    
}

【3】Course.hbm.xml文件:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping package="com.hiber.pojo">
    <class name="Course" table="course_">
        <id name="id" column="id">
            <generator class="native">
            </generator>
        </id>
        <property name="name" />
        
         
        <set name="students" table="sc" lazy="false" >
            <key column="Cid" />
            <many-to-many column="Sid" class="Student" />
        </set>       
                 
    </class>
     
</hibernate-mapping>

【4】Student.hbm.xml文件:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping package="com.hiber.pojo">
    <class name="Student" table="student_">
        <id name="id" column="id">
            <generator class="native">
            </generator>
        </id>
        <property name="name" />
        
         
        <set name="courses" table="sc" lazy="false">
            <key column="Sid" />
            <many-to-many column="Cid" class="Course" />
        </set>       
                 
    </class>
     
</hibernate-mapping>

(2)在src下新建一个.xml文件将其命名为(hibernate.cfg.xml)代码如下:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernn</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        
        <mapping resource="com/hiber/pojo/Student.hbm.xml" />
        <mapping resource="com/hiber/pojo/Course.hbm.xml" />
    </session-factory>
 
</hibernate-configuration>

 

(3):新建包com.hiber.dao在包中写方法(CourseDao类和StudentDao类)代码如下:

【1】CourseDao类:

package com.hiber.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.hiber.pojo.Course;





public class CourseDao {
      public void add(Course p)
      {
    	  Transaction tran = null;
    	  SessionFactory sf = new Configuration().configure().buildSessionFactory();
    	  Session s =sf.openSession();
    	  try {
			  tran=s.beginTransaction();
			  s.save(p);
			  tran.commit();
		} catch (Exception e) {
			// TODO: handle exception
			if(tran!=null)
			{
				tran.rollback();
			}
			e.printStackTrace();
		}finally{
		  s.close();	
		}
      }
      
      public Course get(int id)
      {
    	  Course result=null;
    	  SessionFactory sf = new Configuration().configure().buildSessionFactory();
    	  Session s =sf.openSession();
    	  try {
			 result = (Course)s.get(Course.class, id);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			s.close();
		}
    	  return result;
      }
      
      public void delete(int id){
    	  Transaction tran = null;
    	  SessionFactory sf = new Configuration().configure().buildSessionFactory();
    	  Session s =sf.openSession();
    	  try {
			tran = s.beginTransaction();
			Course p =(Course)s.get(Course.class, id);
			s.delete(p);
			tran.commit();
		} catch (Exception e) {
			// TODO: handle exception
			if(tran!=null)
			{
				tran.rollback();
		    }
			e.printStackTrace();
		}finally{
			s.close();
		}
      }
      
      public void update(Course p)
      {
    	  Transaction tran=null;
    	  SessionFactory sf =new Configuration().configure().buildSessionFactory();
    	  Session s =sf.openSession();
    	  try {
			tran=s.beginTransaction();
			s.update(p);
			tran.commit();
		} catch (Exception e) {
			// TODO: handle exception
			if(tran!=null)
			{
				tran.rollback();
			}
			e.printStackTrace();
		}finally{
			s.close();
		}
      }
    	  
       public List<Course> listProduct() {
    	   List<Course> result = new ArrayList();
    	   SessionFactory sf=new Configuration().configure().buildSessionFactory();
    	   Session s = sf.openSession();
    	   Query q = s.createQuery("from Product p");
    	   result = q.list();
    	   s.close();
    	   sf.close();
    	   return result;
    	   
       }
}

【2】StudentDao类:

package com.hiber.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.hiber.pojo.Student;




public class StudentDao {
      public void add(Student p)
      {
    	  Transaction tran = null;
    	  SessionFactory sf = new Configuration().configure().buildSessionFactory();
    	  Session s =sf.openSession();
    	  try {
			  tran=s.beginTransaction();
			  s.save(p);
			  tran.commit();
		} catch (Exception e) {
			// TODO: handle exception
			if(tran!=null)
			{
				tran.rollback();
			}
			e.printStackTrace();
		}finally{
		  s.close();	
		}
      }
      
      public Student get(int id)
      {
    	  Student result=null;
    	  SessionFactory sf = new Configuration().configure().buildSessionFactory();
    	  Session s =sf.openSession();
    	  try {
			 result = (Student)s.get(Student.class, id);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			s.close();
		}
    	  return result;
      }
      
      public void delete(int id){
    	  Transaction tran = null;
    	  SessionFactory sf = new Configuration().configure().buildSessionFactory();
    	  Session s =sf.openSession();
    	  try {
			tran = s.beginTransaction();
			Student p =(Student)s.get(Student.class, id);
			s.delete(p);
			tran.commit();
		} catch (Exception e) {
			// TODO: handle exception
			if(tran!=null)
			{
				tran.rollback();
		    }
			e.printStackTrace();
		}finally{
			s.close();
		}
      }
      
      public void update(Student p)
      {
    	  Transaction tran=null;
    	  SessionFactory sf =new Configuration().configure().buildSessionFactory();
    	  Session s =sf.openSession();
    	  try {
			tran=s.beginTransaction();
			s.update(p);
			tran.commit();
		} catch (Exception e) {
			// TODO: handle exception
			if(tran!=null)
			{
				tran.rollback();
			}
			e.printStackTrace();
		}finally{
			s.close();
		}
      }
    	  
       public List<Student> listProduct() {
    	   List<Student> result = new ArrayList();
    	   SessionFactory sf=new Configuration().configure().buildSessionFactory();
    	   Session s = sf.openSession();
    	   Query q = s.createQuery("from Product p");
    	   result = q.list();
    	   s.close();
    	   sf.close();
    	   return result;
    	   
       }
}

 

(4):新建一个测试包com.hiber.test并写一个测试类Test(代码如下):

package com.hiber.test;

import java.util.Iterator;

import com.hiber.dao.CourseDao;
import com.hiber.dao.StudentDao;
import com.hiber.pojo.Course;
import com.hiber.pojo.Student;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
       Test test =new Test();
       test.testDelete();
	}
    
	public void testAdd_1(){
		CourseDao cdao =new CourseDao();
		StudentDao sdao=new StudentDao();
		//创建两个Student对象
		Student s1 =new Student();
		s1.setName("Jack");
		Student s2 =new Student();
		s2.setName("Rose");
		//创建四个Course对象
		Course c1 =new Course();
		c1.setName("Java");
		Course c2 =new Course();
		c2.setName("C++");
		Course c3=new Course();
		c3.setName("C#");
		Course c4 =new Course();
		c4.setName("Web");
		//设定s1与c1和c2之间的相互关联
		s1.getCourses().add(c1);
		s1.getCourses().add(c2);
		//设定s2与c1、c3和c4之间的相互关联
		s2.getCourses().add(c1);
		s2.getCourses().add(c3);
		s2.getCourses().add(c4);
		//保存c1、c2、c3和c4
		cdao.add(c1);
		cdao.add(c2);
		cdao.add(c3);
		cdao.add(c4);
		//保存s1和s2对象
		sdao.add(s1);
		sdao.add(s2);
	}
	
	public void testAdd_2(){
		CourseDao cdao =new CourseDao();
		StudentDao sdao=new StudentDao();
		Student s=new Student();
		s.setName("Tom");
		//加载“JAVA”对象
		Course c=(Course)cdao.get(1);
		//设置s和c对象之间的关联
	    s.getCourses().add(c);
	    //保存对象s
	    sdao.add(s);
	    //更新对象c
	    cdao.update(c);
	}
	
	public void testAdd_3(){
		CourseDao cdao =new CourseDao();
		StudentDao sdao=new StudentDao();
		//加载“Jack”和“Rose”对象
		Student s1=(Student)sdao.get(1);
		Student s2=(Student)sdao.get(2);
	    //创建“English”课程对象
		Course c=new Course();
		c.setName("English");
		//设定c与s1和s2对象之间的关联
		s1.getCourses().add(c);
		s2.getCourses().add(c);
		//保存c对象
		cdao.add(c);
		//更新s1和s2
		sdao.update(s1);
		sdao.update(s2);
	}
	
	public void testDelete(){
		CourseDao cdao =new CourseDao();
		StudentDao sdao=new StudentDao();
		//加载“Jack”对象,并获得其选课集合
		Student s=(Student)sdao.get(1);
		Iterator cs=s.getCourses().iterator();
		//删除中介表sc中与“Jack”关联的记录
		while(cs.hasNext()){
			Course c=(Course)cs.next();
			c.getStudents().remove(s);
		}
		//将"Jack"对象删掉
		sdao.delete(1);
	}
}

 4.运行即可

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值