hibernate一对多与多对多示例

文件清单:

文件名

描述

Student.java

学生信息类

Teacher.java

老师信息类

Clazz.java

班级信息类

Student.hbm.xml

学生信息对应映射文件

Teacher.hbm.xml

老师信息对应映射文件

Clazz.hbm.xml

班级信息对应映射文件

Hibernate.cfg.xml

Hibernate配置文件

HibernateUtil.java

Hibernate工具类

Test.java

测试类

 

 

Student.java

import java.util.Set;

 

public class Student {

    private int id;

    private String name;

    private int age;

    private Clazz clazz = null;

    private Set<Teacher> teacs;

   

    public Set<Teacher> getTeacs() {

        return teacs;

    }

    public void setTeacs(Set<Teacher> teacs) {

        this.teacs = teacs;

    }

    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 int getAge() {

        return age;

    }

    public void setAge(int age) {

        this.age = age;

    }

    public Clazz getClazz() {

        return clazz;

    }

    public void setClazz(Clazz clazz) {

        this.clazz = clazz;

    }

}

 

Teacher.java

import java.util.Set;

 

public class Teacher {

    private int id;

    private String name;

    private Set<Student> stus;

   

    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<Student> getStus() {

        return stus;

    }

    public void setStus(Set<Student> stus) {

        this.stus = stus;

    }

}

 

Clazz.java

import java.util.Set;

 

public class Clazz {

    private int id;

    private String name;

    private Set<Student> stus;

   

    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<Student> getStus() {

        return stus;

    }

    public void setStus(Set<Student> stus) {

        this.stus = stus;

    }

}

 

Student.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping

    package="com.xfimti.hiberante.beans">

    <class name="Student">

        <id name="id" >

            <generator class="native"></generator>

        </id>

        <property name="name"></property>

        <property name="age"></property>

       

        <many-to-one name="clazz" column="clazz_id"></many-to-one>

        <set table="stu_tea" name="teacs">

            <key column="student_id"></key>

            <many-to-many class="Teacher" column="teacher_id"></many-to-many>

        </set>

    </class>

   

</hibernate-mapping>

 

Teacher.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping

    package="com.xfimti.hiberante.beans">

    <class name="Teacher">

        <id name="id" >

            <generator class="native"></generator>

        </id>

        <property name="name"></property>

       

        <set table="stu_tea" name="stus">

            <key column="teacher_id"></key>

            <many-to-many class="Student" column="student_id"></many-to-many>

        </set>

    </class>

   

</hibernate-mapping>

 

 

Clazz.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping

    package="com.xfimti.hiberante.beans">

    <class name="Clazz">

        <id name="id" >

            <generator class="native"></generator>

        </id>

        <property name="name"></property>

        <set name="stus" inverse="true">

            <key column="clazz_id"></key>

            <one-to-many class="Student"/>

        </set>

    </class>

   

</hibernate-mapping>

 

 

Hibernate.cg.xml

<!DOCTYPE hibernate-configuration PUBLIC

    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

 

<hibernate-configuration>

<session-factory name="foo">

    <property name="show_sql">true</property>

    <property name="hibernate.format_sql">false</property>

 

    <property name="hibernate.hbm2ddl.auto">update</property>

 

    <property name="hibernate.connection.driver_class">

        com.mysql.jdbc.Driver

    </property>

    <property name="hibernate.connection.url">

        jdbc:mysql:///test

    </property>

    <property name="hibernate.connection.username">root</property>

    <property name="hibernate.connection.password">123</property>

    <property name="hibernate.dialect">

        org.hibernate.dialect.MySQLDialect

    </property>

    <mapping resource="com/xfimti/hiberante/beans/Student.hbm.xml" />

    <mapping resource="com/xfimti/hiberante/beans/Clazz.hbm.xml" />

    <mapping resource="com/xfimti/hiberante/beans/Teacher.hbm.xml" />

</session-factory>

</hibernate-configuration>

 

HibernateUtil.java

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

 

public class HibernateUtil {

    private static SessionFactory sessionFactory = null;

   

    static {

        try {

            sessionFactory = new Configuration().configure().buildSessionFactory();

        } catch (HibernateException e) {

             System.err.println("Initial SessionFactory creation failed." + e);

            e.printStackTrace();

        }

    }

   

    public static Session getSession() {

        return sessionFactory.openSession();

    }

}

 

Test.java

import java.util.ArrayList;

import java.util.HashSet;

import java.util.List;

import java.util.Set;

 

import org.hibernate.HibernateException;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.Transaction;

 

import com.xfimti.hiberante.beans.Clazz;

import com.xfimti.hiberante.beans.Student;

import com.xfimti.hiberante.beans.Teacher;

import com.xfimti.hibernate.util.HibernateUtil;

 

public class Test {

   

    public static void main(String[] args) {

        /*一对多示例。*/

        /*List<Student> ss = getAllStudent(3);

        System.out.println(ss.size());

        Iterator<Student> its = ss.iterator();

        while(its.hasNext()) {

            Student s = its.next();

            System.out.println(s.getName()+","+s.getAge());

        }*/

       

        /*多对多示例。*/

        /*添加一个老师的信息。*/

        /*Teacher t = new Teacher();

        t.setName("teacher1");

        addTeacher(t);*/

       

        /*添加一个班级信息。*/

        /*Clazz clazz = new Clazz();

        clazz.setName("xxxxxx");

        addClazz(clazz);*/

       

        /*添加一个学生信息。他的老师是teacher1,所在班级为xxxxxx*/

        Student s = new Student();

        s.setName("yyyyyy");

        String clazzName = "xxxxxx";

        String teacherName = "teacher1";

        addStudent(s, clazzName, teacherName);

    }

   

    /**根据班级名称查询出班级信息。*/

    public static Clazz getClazz(String name) {

        Clazz clazz = null;

        Session s = HibernateUtil.getSession();

        Query q = s.createQuery("from Clazz as c where c.name=?");

        q.setString(0, name);

        clazz = (Clazz) q.uniqueResult();

        if(s != null) {

            s.close();

        }

        return clazz;

    }

   

    /**添加学生信息。*/

    public static void addStudent(Student stu,String clazzName) {

        Session session = null;

        Transaction tx = null;

       

        try {

            session = HibernateUtil.getSession();

            tx = session.beginTransaction();

            session.saveOrUpdate(stu);

            Clazz clazz = getClazz(clazzName);

            stu.setClazz(clazz);

            tx.commit();

        } catch (HibernateException e) {

            if(tx != null) {

                tx.rollback();

            }

            e.printStackTrace();

        }

        finally{

            if(session != null) {

                session.close();

            }

        }

    }

   

    /**添加班级信息。*/

    public static void addClazz(Clazz clazz) {

        Session session = null;

        Transaction tx = null;

       

        try {

            session = HibernateUtil.getSession();

            tx = session.beginTransaction();

            session.save(clazz);

            tx.commit();

        } catch (HibernateException e) {

            if(tx != null) {

                tx.rollback();

            }

            e.printStackTrace();

        }

        finally{

            if(session != null) {

                session.close();

            }

        }

    }

   

    /**通过班级编号,查询出该班级所有的学生信息。*/

    public static List<Student> getAllStudent(int clazz_id) {

        List<Student> ss = new ArrayList<Student>();

        Session s = HibernateUtil.getSession();

        Clazz clazz = (Clazz) s.get(Clazz.class, 3);

        for (int i = 0; i < clazz.getStus().size(); i++) {

            ss.add((Student)clazz.getStus().toArray()[i]);

        }

        return ss;

    }

 

    /**添加老师信息*/

    public static void addTeacher(Teacher t) {

        Session session = null;

        Transaction tx = null;

       

        try {

            session = HibernateUtil.getSession();

            tx = session.beginTransaction();

            session.save(t);

            tx.commit();

        } catch (HibernateException e) {

            if(tx != null) {

                tx.rollback();

            }

            e.printStackTrace();

        }

        finally{

            if(session != null) {

                session.close();

            }

        }

    }

   

    /**添加学生信息。多对多*/

    public static void addStudent(Student s,String clazzName,String teacherName) {

        Session ss = null;

        Transaction tx = null;

        try {

            ss = HibernateUtil.getSession();

            tx = ss.beginTransaction();

            ss.save(s);

            /*根据班级名称查出班级信息。*/

            Query q = (Query) ss.createQuery("from Clazz where name=?");

            q.setString(0, clazzName);

            Clazz clazz = (Clazz) q.uniqueResult();

            q = null;

            /*根据老师姓名查出老师信息。*/

            q = ss.createQuery("from Teacher where name=?");

            q.setString(0, teacherName);

            Teacher t = (Teacher) q.uniqueResult();

            s.setClazz(clazz);

            /*clazzt设置到s,在处理持久化状态自动检测更改并修改。*/

            Set<Teacher> st = new HashSet<Teacher>();

            st.add(t);

            s.setTeacs(st);

            tx.commit();

        } catch (HibernateException e) {

            if(tx != null) {

                tx.rollback();

            }

            e.printStackTrace();

        }finally {

            if(ss != null) {

                ss.close();

            }

        }

    }

 

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值