为了账号安全,请及时绑定邮箱和手机立即绑定

Hibernate多对多关联映射demo--以student和course生成sc表为例

标签:
Java

开始之间说两句:
这个student对course是多对多的关系,多对多关联映射有两种情况:第一种情况,<many-to-many>的情况,生成第三个表,但是第三个表没有实际效用,故而没有第三个实际存在的类。第二种情况,多对多关联映射拆分<many-to-one><one-to-many>的情况,也就是我们现在说的这种情况,sc表有效用,需要用到sc表,所以需要创建Sc.java,。

1.那么我们开始新建工程吧。工程目录如下:
图片描述
2.确认映射关系
图片描述
3.编写java文件

/*************Course.java*****************/
package com.feng.dao;

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

public class Course {

    private Integer cno;
    private String cname;

    private Set<Student> students =new HashSet<Student>(0);

    public Integer getCno() {
        return cno;
    }
    public void setCno(Integer cno) {
        this.cno = cno;
    }
    public String getCname() {
        return cname;
    }
    public void setCname(String cname) {
        this.cname = cname;
    }
    public Set<Student> getStudents() {
        return students;
    }
    public void setStudents(Set<Student> students) {
        this.students = students;
    }
}
/***************Sc.java******************/
package com.feng.dao;

public class Sc {

    private Integer grade;

    private Student student;
    private Course course;

    public Integer getGrade() {
        return grade;
    }
    public void setGrade(Integer grade) {
        this.grade = grade;
    }
    public Student getStudent() {
        return student;
    }
    public void setStudent(Student student) {
        this.student = student;
    }
    public Course getCourse() {
        return course;
    }
    public void setCourse(Course course) {
        this.course = course;
    }

}
/*************Student.java********************/
package com.feng.dao;

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

public class Student {

    private Integer sno;
    private String sname;
    private String ssex;

    private Set<Course> courses=new HashSet<Course>(0);

    public Integer getSno() {
        return sno;
    }

    public void setSno(Integer sno) {
        this.sno = sno;
    }

    public String getSname() {
        return sname;
    }

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

    public String getSsex() {
        return ssex;
    }

    public void setSsex(String ssex) {
        this.ssex = ssex;
    }

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

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

}

4.创建数据库表
图片描述
图片描述
图片描述

5.创建hibernatejava类同数据库table的映射文件student.hbm.xmlcourse.hbm.xml,sc.hbm.xml,分别依次如下所示:

<?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 package="com.feng.dao">
    <class name="Student" table="student">
        <id name="sno">
            <column name="sno" sql-type="int"></column>
            <generator class="increment" ></generator>
        </id>
        <property name="sname" type="java.lang.String" column="sname"/>
        <property name="ssex" type="java.lang.String" column="ssex"></property>
        <!-- 实现了对sc表中的映射 -->
        <set name ="courses" cascade="all" table="sc">
            <key column="cno"></key>
            <one-to-many class="Course"></one-to-many>
        </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">
<hibernate-mapping package="com.feng.dao">
    <class name="Course" table="course">
        <id name="cno">
            <column name="cno" sql-type="int"></column>
            <generator class="increment" ></generator>
        </id>
        <property name="cname" type="java.lang.String" column="cname"/>
        <set name ="students" cascade="all" table="sc">
            <key column="sno"></key>
            <one-to-many class="Student"></one-to-many>
        </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">
<hibernate-mapping package="com.feng.dao">
    <class name="Sc" table="sc">
        <id name="grade">
            <column name="grade" sql-type="int"></column>
        </id>
        <many-to-one name="student" class="Student" column="sno" cascade="all"></many-to-one>
        <many-to-one name="course" class="Course" column="cno" cascade="all"></many-to-one>
    </class>
</hibernate-mapping>

6.创建工程对数据库的映射即hibernate.cfg.xml文件

<!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ License: 
    GNU Lesser General Public License (LGPL), version 2.1 or later. ~ See the 
    lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. -->
<!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>
        <!--mysql database -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/student</property>
        <!-- student is your database. -->
        <property name="connection.username">root</property>
        <!-- Account is root. -->
        <property name="connection.password"></property>
        <!-- Password is null. -->
        <property name="connection.characterEncoding">utf8</property>
        <!-- Encoding is utf8. -->
        <property name="connection.pool_siez">10</property>
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <!-- This represents the connection to the database. -->
        <mapping resource="com/feng/dao/student.hbm.xml" />
        <mapping resource="com/feng/dao/course.hbm.xml" />
        <mapping resource="com/feng/dao/sc.hbm.xml" />
    </session-factory>
</hibernate-configuration>

8.创建测试类,Test.java

package com.feng.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import com.feng.dao.Course;
import com.feng.dao.Sc;
import com.feng.dao.Student;

public class Test {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // 1.进行配置文件的读取
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();
        StandardServiceRegistry sr = ssrb.configure().build();
        // 2.由config得到一个会话工厂//得到sessionFactory
        SessionFactory sf = new MetadataSources(sr).buildMetadata().buildSessionFactory();
        // 3.由sessionFacatory得到session
        Session session = sf.openSession();
        /*
         * 开启事务,增删改都需要事务
         */
        Transaction tran = session.beginTransaction(); // 不但得到事务的对象而且还开启了,,还可以session.getTransaction().begin();
//      
        Student s =new Student();
        s.setSname("lisi");
        s.setSsex("women");

        Course c =new Course();
        c.setCname("China");

        Sc sc =new Sc();
        sc.setGrade(100);

        s.getCourses().add(c);
        c.getStudents().add(s);

        sc.setCourse(c);
        sc.setStudent(s);

        session.save(sc);

        tran.commit(); // 一定要提交事务!!!!!!!
        // 4.记得关闭session
        session.close();
        sf.close();

    }
}

9.执行成功
在sc、student、course表中各自插入了一条数据,这里就不再展示了

10.思考:此处就有一个疑问了,我在sc.hbm.xml文件中写的级联映射为all,那么,会不会删除sc表中的数据,同时student和course表中的数据同样删去了呢?来实现一下:
Test.javamain函数中,
事务之间写入:

Sc sc =new Sc();
sc.setGrade(100);
session.delete(sc);

运行之后发现,sc表中删除了这条数据,但是student表和course表中没有删除数据,所以,在sc表中删除数据,不会影响student表和course表,这符合逻辑性。

学习不息,代码不止,加油!!!!
点击查看更多内容
2人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消