hibernate建表多对多建表

Student.java

package cn.itcast.hiberate.sh.domain;

import java.util.Set;

public class Student {
    private Long sid;
    private String sname;
    private String description;
    Set<Course> courses;


    public Set<Course> getCourses() {
        return courses;
    }
    public void setCourses(Set<Course> courses) {
        this.courses = courses;
    }
    public Long getSid() {
        return sid;
    }
    public void setSid(Long sid) {
        this.sid = sid;
    }
    public Student(String sname, String description) {
        super();
        this.sname = sname;
        this.description = description;
    }
    public Student() {
        // TODO Auto-generated constructor stub
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

}

Student.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>
    <class name="cn.itcast.hiberate.sh.domain.Student">
        <id name="sid" length="5">
            <generator class="increment"></generator>
        </id>
        <property name="sname" length="20"></property>
        <property name="description" length="100"></property>
        <!-- 
            table就是用来描述第三张表
            key 用来描述外键,多对多的关系看对哪张表建立映射
            此表是描述Student信息的,所以 key中 column写sid

            many-to-many 中用于建立关系的所以 在第三张表中关系用cid建立
         -->
        <set name="courses" table="student_course">
            <key>
                <column name="sid"></column>
            </key>
            <many-to-many class="cn.itcast.hiberate.sh.domain.Course" column="cid">
            </many-to-many >
        </set>
    </class>
</hibernate-mapping>

Course.java

package cn.itcast.hiberate.sh.domain;

import java.io.Serializable;
import java.util.Set;

public class Course implements Serializable {
    private Long cid;
    private String cname;
    private String description;
    private Set<Student> students;
    public Long getCid() {
        return cid;
    }
    public void setCid(Long cid) {
        this.cid = cid;
    }
    public String getCname() {
        return cname;
    }
    public void setCname(String cname) {
        this.cname = cname;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public Set<Student> getStudents() {
        return students;
    }
    public void setStudents(Set<Student> students) {
        this.students = students;
    }

}

Course.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>
    <class name="cn.itcast.hiberate.sh.domain.Course">
        <id name="cid" length="5" type="java.lang.Long">
            <generator class="increment"></generator>
        </id>
        <property name="cname" length="20" type="java.lang.String"></property>

        <property name="description" length="100" type="java.lang.String"></property>
        <!-- 
            set元素对应类中的set集合
            通过set元素使classes表与student表建立关联
               key是通过外键的形式让两张表建立关联,针对的是哪张表看哪个
               one-to-many是通过类的形式让两个类建立关联

           1、 cascade 级联
             (1) save-update:
                        当保存班级的时候,对学生进行怎么样的操作
                        如果学生对象在数据库中没有对应的值,这个时候会执行save操作
                        如果学生对象在数据库中有对应的值,这个时候会执行update操作
              (2) delete: 删除时,三张表中的相关内容全部删除
              (3) all:包含(1)、(2)两项
            2、inverse  维护关系(一般选false)
               true      不维护关系     
               false     维护关系
               default   false
         -->
        <set name="students" table="student_course">
            <!-- 
                key是用来描述外键 哪张表就哪個外鍵
                <many-to-many> 中的cid 描述类与类之间的关系
             -->
            <key>
                <column name="cid"></column>
            </key>
            <many-to-many class="cn.itcast.hiberate.sh.domain.Student" column="sid">
            </many-to-many>
        </set>
    </class>
</hibernate-mapping>

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只能连接一个数据库
    -->
<session-factory>
    <!-- 
        数据库的用户名
    -->
    <property name="connection.username">root</property>
    <!-- 
        密码
    -->
    <property name="connection.password">friends</property>
    <!-- 
        url
    -->
    <property name="connection.url">
        jdbc:mysql://localhost:3306/itcast_sh_hibernate_manyTomany
    </property>
    <!-- 
        作用:根据持久化类和映射文件生成表
        validate
        create-drop
        create
        update
    -->
    <property name="hbm2ddl.auto">update</property>
    <!-- 
        显示hibernate内部生成的sql语句
    -->

    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <mapping resource="cn/itcast/hiberate/sh/domain/Course.hbm.xml" />
    <mapping resource="cn/itcast/hiberate/sh/domain/Student.hbm.xml" />

</session-factory>
</hibernate-configuration>

test.java

package cn.itcast.hiberate.sh.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import cn.itcast.hibernate.sh.utils.HiberanteUtils;

public class CreateTable extends HiberanteUtils{

    @Test
    public void createTable()
    {
        Configuration config=new Configuration();
        config.configure();
//        SessionFactory sessionFactory=config.buildSessionFactory();
//        Session session=sessionFactory.openSession();
//        Transaction transaction=session.beginTransaction();
//        
//        
//        transaction.commit();
//        session.close();
    }
}

测试2

package cn.itcast.hibernate.sh.test;

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

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.hiberate.sh.domain.manytomany.Course;
import cn.itcast.hiberate.sh.domain.manytomany.Student;
import cn.itcast.hibernate.sh.utils.HiberanteUtils;

/**
 * 1、新建一个课程
 * 2、新建一个学生
 * 3、新建课程的同时新建学生 级联
 * 4、已经存在一个课程,新建一个学生,建立课程和学生之间的关系
 * 5、已经存在一个学生,新建一个课程,建立课程和学生之间的关系
 * 6、已经存在一个课程,已经存在一个学生,建立关联
 * 7、把已经存在的一些学生加入到已经存在的一个课程中
 * 8、把一个学生加入到一些课程中
 * 9、把多个学生加入到多个课程中
 * 10、把一个已经存在的学生从一个已经的课程中移除
 * 11、把一些学生从一个已经存在的课程中移除
 * 12、把一个学生从一个课程转向到另外一个课程
 * 13、删除课程
 * 14、删除学生
 * @author Think
 *
 */
public class ManyToManyTest extends HiberanteUtils{
    static{
        url = "cn/itcast/hiberate/sh/domain/manytomany/hibernate.cfg.xml";
    }
    @Test
    public void testCreateTable(){

    }

    @Test
    public void testSaveStudent_Cascade_Course_Save(){
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Student student = new Student();
        student.setSname("班长");
        student.setDescription("牛人");

        Course course = new Course();
        course.setCname("生理卫生");
        course.setDescription("很好");

        Set<Course> courses = new HashSet<Course>();
        courses.add(course);
        student.setCourses(courses);
        session.save(student);
        transaction.commit();
        session.close();
    }

    /**
     * 已经存在一个课程,新建一个学生,建立课程和学生之间的关系
     *    从课程角度出发
     */
    @Test
    public void testUpdateCourse_Cascade_Student_Save_R(){
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Course course = (Course)session.get(Course.class, 1L);
        Student student = new Student();
        student.setSname("班迷");
        student.setDescription("班丝:班长的钢丝");
        course.getStudents().add(student);
        session.save(student);
        transaction.commit();
        session.close();
    }

    /**
     * 已经存在一个课程,新建一个学生,建立课程和学生之间的关系
     *   从学生角度出发
     */
    @Test
    public void testSaveStudent_R(){
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Course course = (Course)session.get(Course.class, 1L);
        Student student = new Student();
        student.setSname("班迷");
        student.setDescription("班丝:班长的钢丝");
        Set<Course> courses = new HashSet<Course>();
        courses.add(course);
        student.setCourses(courses);
        session.save(student);
        transaction.commit();
        session.close();
    }

    /**
     * 已经存在一个课程,已经存在一个学生,建立关联
     */
    @Test
    public void testR(){
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Course course = (Course)session.get(Course.class, 1L);
        Student student = (Student)session.get(Student.class, 2L);
        student.getCourses().add(course);
        transaction.commit();
        session.close();
    }

    /**
     * 把学生3,4加入到课程1中
     */
    @Test
    public void testR_Some(){
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Course course = (Course)session.get(Course.class, 1L);
        Student student = (Student)session.get(Student.class, 3L);
        Student student2 = (Student)session.get(Student.class, 4L);
        //注释的语句效率不如没有注释的语句,因为hibernate存在缓存,对于不同的对象student.getcourse()查询了两次sql语句
        //而course.getStudent()则之执行一次查询语句
//        student.getCourses().add(course);
//        student2.getCourses().add(course);
        course.getStudents().add(student2);
        course.getStudents().add(student);
        transaction.commit();
        session.close();
    }

    /**
     * 把一个学生加入到一些课程中
     */
    @Test
    public void testR_Some_2(){
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Student student = (Student)session.get(Student.class, 3L);
        List<Course> courseList = session.createQuery("from Course where cid in(1,2,3)").list();
        student.getCourses().addAll(courseList);
        transaction.commit();
        session.close();
    }

    /**
     * 把学生从一个课程转移到另外一个课程
     */
    @Test
    public void testTransform(){
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Student student = (Student) session.get(Student.class, 3L);
        Course course1 = (Course)session.get(Course.class, 1L);
        Course course3 = (Course)session.get(Course.class, 3L);
        student.getCourses().remove(course1);
        student.getCourses().add(course3);
        transaction.commit();
        session.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值