Hibernate(八)多对多映射

一、创建数据表

--学生证表
create table paper
(
       pid   number primary key,
       pdesc varchar2(100)  ,
       sid   number references student(sid) not null

);
--课程表
create table course
(
       cid                     int          primary key,
       cname                   varchar2(50),
       cdesc                   varchar2(200)
);
--学生生和课程表的中间表
create table sc
(
       sid   number            references student(sid),
       cid   int                references course(cid)
);

二、创建持久化类和配置文件

学生类

package entity;

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

/*
 * 学生类
 */
public class Student implements java.io.Serializable {

    // Fields

    private static final long serialVersionUID = 1L;
    private int sid;
    private String sname;
    private String sex;
    //增加班级属性
    private Grade grade;
    //学生证类
    private Paper paper;
    //添加课程
    private Set<Course> courses=new HashSet<Course>();

    // Constructors

    /** default constructor */
    public Student() {
    }

    /** minimal constructor */
    public Student(int sid) {
        this.sid = sid;
    }

    /** full constructor */
    public Student(int sid, String sname, String sex ) {

        this.sid = sid;

        this.sname = sname;
        this.sex = sex;
    }

    // Property accessors

    public int getSid() {
        return this.sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return this.sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getSex() {
        return this.sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Grade getGrade() {
        return grade;
    }

    public void setGrade(Grade grade) {
        this.grade = grade;
    }

    public Paper getPaper() {
        return paper;
    }

    public void setPaper(Paper paper) {
        this.paper = paper;
    }

    public Set<Course> getCourses() {
        return courses;
    }

    public void setCourses(Set<Course> courses) {
        this.courses = courses;
    }

}

课程类

package entity;

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

/**
 * 课程类
 */

public class Course implements java.io.Serializable {

    // Fields

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private int cid;
    private String cname;
    private String cdesc;
    private Set<Student> students = new HashSet<Student>();

    // Constructors

    /** default constructor */
    public Course() {
    }

    /** minimal constructor */
    public Course(int cid) {
        this.cid = cid;
    }

    /** full constructor */
    public Course(int cid, String cname, String cdesc, Set <Student>students) {
        this.cid = cid;
        this.cname = cname;
        this.cdesc = cdesc;
        this.students = students;
    }

    // Property accessors

    public int getCid() {
        return this.cid;
    }

    public void setCid(int cid) {
        this.cid = cid;
    }

    public String getCname() {
        return this.cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public String getCdesc() {
        return this.cdesc;
    }

    public void setCdesc(String cdesc) {
        this.cdesc = cdesc;
    }

    public Set<Student> getStudents() {
        return students;
    }

    public void setStudents(Set<Student> students) {
        this.students = students;
    }

}

hibernate.cfg.xml

<?xml version=‘1.0‘ encoding=‘UTF-8‘?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>
        <property name="dialect">
            org.hibernate.dialect.Oracle9Dialect
        </property>
        <property name="connection.url">
            jdbc:oracle:thin:@localhost:1521:orcl
        </property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.driver_class">
            oracle.jdbc.OracleDriver
        </property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>

        <mapping resource="entity/Grade.hbm.xml" />
        <mapping resource="entity/Student.hbm.xml" />
        <mapping resource="entity/Paper.hbm.xml" />
        <mapping resource="entity/Course.hbm.xml" />

    </session-factory>

</hibernate-configuration>

学生类配置文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="entity.Student" table="STUDENT" schema="ROOT">
        <id name="sid" type="java.lang.Integer">
            <column name="SID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="sname" type="java.lang.String">
            <column name="SNAME" length="20" />
        </property>
        <property name="sex" type="java.lang.String">
            <column name="SEX" length="20" />
        </property>
        <!--配置grade属性  -->
        <many-to-one name="grade" class="entity.Grade" cascade="save-update">
        <!--指定学生表中的外键  -->
        <column name="GID" />
        </many-to-one>
        <!-- 添加学生证的配置 -->
        <one-to-one name="paper" class="entity.Paper" cascade="all" lazy="false" property-ref="student"/>
        <!--添加课程  -->
           <set name="courses" cascade="save-update" table="SC">
           <key column="sid" />
           <many-to-many class="entity.Course" column="cid"/>
           </set>
    </class>
</hibernate-mapping>

课程类配置文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="entity.Course" table="COURSE" schema="ROOT">
        <id name="cid" type="java.lang.Integer">
            <column name="CID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="cname" type="java.lang.String">
            <column name="CNAME" length="50" />
        </property>
        <property name="cdesc" type="java.lang.String">
            <column name="CDESC" length="200" />
        </property>
        <set name="students"  table="SC" cascade="save-update" inverse="true">
            <key column="cid" />
            <many-to-many class="entity.Student" column="sid" />
        </set>
    </class>
</hibernate-mapping>

测试类

package Test;

import java.util.Set;

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

import entity.Course;
import entity.Student;

public class Demo7 {

    public static void main(String[] args) {
        delte();

    }
    public static void save(){
        Student stu1 = new Student();
        stu1.setSid(201503011);
        stu1.setSname("赵云");
        stu1.setSex("男");

        //课程
        Course c1=new Course();
        c1.setCid(1111);
        c1.setCname("长枪阵");
        c1.setCdesc("杀进杀出");

        Course c2=new Course();
        c2.setCid(2222);
        c2.setCname("大刀");
        c2.setCdesc("青龙偃月刀");

        stu1.getCourses().add(c1);
        stu1.getCourses().add(c2);

        Session session =new Configuration().configure().buildSessionFactory().openSession();
        Transaction tran=session.beginTransaction();
        session.save(stu1);

        tran.commit();
        session.close();
    }

    public static void find(){

        Session session =new Configuration().configure().buildSessionFactory().openSession();
        Course c=(Course) session.get(Course.class, 1111);
        System.out.println(c.getCid()+"\t"+c.getCname()+"\t"+c.getCdesc());
        Set<Student> stus=c.getStudents();
        for (Student s : stus) {
            System.out.println(s.getSname());
        }
        session.close();
    }

    public static void update(){

        Session session =new Configuration().configure().buildSessionFactory().openSession();
        Student stu=(Student) session.get(Student.class, 201509009);

        Course cou=(Course) session.get(Course.class, 2222);

        Transaction tran=session.beginTransaction();
        stu.getCourses().add(cou);
        session.update(stu);
        tran.commit();
        session.close();
    }
    public static void delte(){
        Session session =new Configuration().configure().buildSessionFactory().openSession();
        Student stu=(Student) session.get(Student.class, 201509009);

        Course cou=(Course) session.get(Course.class, 2222);

        Transaction tran=session.beginTransaction();
        stu.getCourses().remove(cou);
        session.update(stu);
        tran.commit();
        session.close();
    }

}

时间: 2024-10-03 07:33:55

Hibernate(八)多对多映射的相关文章

(08)Hibernate的多对多映射配置

基本需求是:一个项目可以有多个开发人员,一个开发人员可以参加多个项目,因此项目和开发人员是多对多的关系.本文中的学习重点,还和前几篇文章一样,都是JavaBean类的映射文件中的配置. 1.多对多映射 Project.java package com.rk.hibernate.h_many2many; import java.util.Set; public class Project { private int prjId; private String prjName; private Se

Hibernate的多对一映射

一.创建Java工程,新建Lib文件夹,加入Hibernate和数据库(如MySql.Oracle.SqlServer等)的Jar包,创建 hibernate.cfg.xml 文件,并配置,配置项如下: 1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configura

Hibernate的多对多映射关系

example: 老师(teacher)和学生(Student)就是一个多对多的关系吧?老师可以有多个学生,学生也可以由多个老师,那在Hibernate中多对多是怎样实现的呢?? 在Hibernate中多对多关系分为两种:1单向的多对多,2双向的多对多 下面详细说明一些两种有什么不同和实现步骤 I单向的多对多实现步骤: 1新建teacher.student表,可以任意选择在其中一个表添加另一个表的集合,(例如在teacher中添加student的set<Student>集合,例如private

Hibernate单向多对一映射关系(1)

单向 n-1 单向 n-1 关联只需从 n 的一端可以访问 1 的一端 域模型: 从 Order 到 Customer 的多对一单向关联需要在Order 类中定义一个 Customer 属性, 而在 Customer 类中无需定义存放 Order 对象的集合属性 关系数据模型:ORDERS 表中的 CUSTOMER_ID 参照 CUSTOMER 表的主键        Order.hbm.xml <many-to-one name="customer" class="C

Hibernate 单项多对一映射

public class Order { private Integer orderId; private String orderName; private Customer customer; } public class Customer { private Integer customerId; private String sustomerName; } 在映射多对一的关联关系时,使用 many-to-one 来映射多对一的关联关系. <many-to-one name="cus

hibernate关于多对多映射和多对一的hql查询

public void queryCustomerbymerchantId(){ SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.getCurrentSession(); Transaction ts = session.beginTransaction(); try { Query query=session.createQuery("select c from Customer c joi

【Hibernate步步为营】--多对多映射具体解释

上篇文章具体讨论了一对多映射,在一对多映射中单向的关联映射会有非常多问题,所以不建议使用假设非要採用一对多的映射的话能够考虑使用双向关联来优化之间的关系,一对多的映射事实上质上是在一的一端使用<many-to-one>标签来标明它们之间的关系,另外还须要在一的一端的对象中使用set标明集合映射. 一.单向多对多 仍然依照前几篇的文章格式来讨论.首先来看对象之间的关系,单向的多对多关系是两个对象之间发生的,比方在人和职位之间,一个人能够有多个职位,并且一个职位也能够由多人来负责,所以它们之间就形

【SSH高速进阶】——Hibernate 多对多映射

说到多对多关系.印象最深刻的就是大学的选修课.一个学生能够选修多门课程,一门课程能够有多个学生选修,学生所选的每一门课程还有成绩. 这个场景的E-R图例如以下: 对于多对多的关系,我们一般会抽出一张中间表(连接表),来负责维护这两张表的多对多关系.比方上述关系应该生成的表结构为: PO对象 Student.java public class Student { private int id; private String name; private Set<Course> courses; /

Hibernate中的一对多与多对一映射

1.需求 一个部门有多个员工;         [一对多] 多个员工,属于一个部门    [多对一] 2.实体Bean设计 Dept: public class Dept { private int depId; private String depName; private Set<Employee> emps = new HashSet<Employee>(); set... get... } Employee: public class Employee { private