码迷,mamicode.com
首页 > Web开发 > 详细

hibernate入门三之关联映射(一对多和多对一)

时间:2019-06-09 18:10:32      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:code   class   size   duti   学生   java   div   gets   三生   

提示;本文的操作是在入门一和二上面的

hibernate对映射类型

在开始是学习的时候,我以为一对多和多对一是同样的,后来发现不是这样,比如说班主任和班级里的学生,一个班级可能有多个学生,但是只有一个班主任,学生和班主任的关系是多对一,班主任和学生的关系是一对多,两者之间的区别在于它们的指向性

  • 一对一(one-to-one )
  • 一对多(ont-to-many)
  • 多对一(many-to-one)
  • 多对多(many-to-many)

一对多(ont-to-many)和多对一(many-to-one)最常见和做常用的映射类型

 

一对多(ont-to-many)

1、创建班级表和学生表,通过外键进行关联(

alter table Students add constraint fk_students_gid foreign key (gid) references grade(gid);

技术图片

 

2、创建班级表和学生表的实体类(属性/默认构造器、带参构造器、get和set方法,toString方法)

private int gid;
private String gname;
private String gdesc;
// 在一方定义一个多方的集合
private Set<Students> students = new HashSet<Students>();
//其他。。。略 }

 

public class Students {

    private int sid;
    private String sname;
    private String gender;
    private Date birthday;
    //private String address;
    private Blob pictur;
    private Address address;

//其他。。。略
}

 3、创建Grade.hbm.xml(我的Stuendt.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="com.hibernate.entity.Grade" table="grade">
        <id name="gid" column="gid" type="int">
            <generator class="increment"></generator>
        </id>
        <property name="gname" type="java.lang.String">
            <column name="gname"/>
        </property>
        <property name="gdesc" type="java.lang.String">
            <column name="gdesc"/>
        </property>
        <!--单项的一对多的关系-->
        <set name="students" table="Students">
            <!--指定的关联外键列-->
            <key column="gid"></key>
            <one-to-many class="com.hibernate.entity.Students"/>
        </set>

    </class>


</hibernate-mapping>

 4、在cfg.xml中配置映射文件路径

<!--指定映射文件的路径-->
    <mapping resource="com/hibernate/entity/Grade.hbm.xml"/>
    <mapping resource="com/hibernate/entity/Students.hbm.xml"/>

 5、创建HibernateUtil类

public class HibernadUtil {

    private static SessionFactory sessionFactory;
    private static Session session;

    static {
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
        sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
    }

    //获取SessionFacory
    public static SessionFactory getSessionFacory() {
        return sessionFactory;
    }

    //获取session
    public static Session getSession() {

        return sessionFactory.openSession();
    }

    //关闭session
    public static void closeSession(Session session) {
        if (null != session) {
            session.close();
        }
    }

 6、进行测试

 

public class TestStudentsAndGrade {

    public static void main(String[] args) {
        //add();
        //findStudensByGrade();
        //update();
        deleteStudentsBySid();
    }

    //给表中插入数据
    public static void add() {
        Grade grade = new Grade("道班", "道一");
        Students s = new Students("道一", "男", new Date());
        Students s2 = new Students("阴阳", "男", new Date());
        Students s3 = new Students("三生", "女", new Date());
        System.out.println(grade.getStudents().add(s));
        //如果希望在学生表中添加对应道班级编号,需要在班级中添加学生,建立关联关系
        grade.getStudents().add(s);
        grade.getStudents().add(s2);
        grade.getStudents().add(s3);

        Session session = HibernadUtil.getSession();
        //开启事务
        Transaction transaction = session.beginTransaction();
        session.save(grade);
        session.save(s);
        session.save(s2);
        session.save(s3);
        transaction.commit();
        HibernadUtil.closeSession(session);
    }

    //查询班级中包含的学生
    public static void findStudensByGrade() {
        //获取session
        Session session = HibernadUtil.getSession();
        //获取班级信息
        Grade grade = session.get(Grade.class, 1);
        //输出班级信息
        System.out.println(grade.getGname() + "," + grade.getGdesc());

        //找出班级信息,然后找出班级学生信息
        Set<Students> students = grade.getStudents();
        for (Students stu:students
             ) {
            System.out.println(stu);
        }
    }

    //修改学生信息
    public static void update(){
        Grade grade =new Grade("道","道二");
        Session session = HibernadUtil.getSession();
        Transaction transaction = session.beginTransaction();

        //修改学生所在班级信息(grade班级信息为自增长,别一不小心玩过头了)
        Students students = session.get(Students.class, 2);
        grade.getStudents().add(students);
        session.save(grade);
        transaction.commit();
        HibernadUtil.closeSession(session);
    }

    //从班级中删除学生信息
    public static  void deleteStudentsBySid(){

        Session session = HibernadUtil.getSession();
        Transaction transaction = session.beginTransaction();
        Students students = session.get(Students.class,9);
        session.delete(students);
        transaction.commit();
        HibernadUtil.closeSession(session);

    }

}

 7、一对多中的set元素属性

技术图片

多对一(many-to-one)

 

hibernate入门三之关联映射(一对多和多对一)

标签:code   class   size   duti   学生   java   div   gets   三生   

原文地址:https://www.cnblogs.com/lindaiyu/p/10994131.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!