package com.ddwei.entity;

import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.ddwei.util.HibernateUtil;

/**
 * 建立关联关系后,
 * 可以方便的从一个导航对象,关联到另一个导航对象!
 * 注意关联方向:一对多
 * @author weijingli
 *
 */
public class Test {
    
    public static void main(String[] args) {
//        add();
        show();
    }
    
    
    //增加班级学生信息
    public static void add(){
        
        Grade g = new Grade("java一班","java一班是一个好班");
        Student stu1 = new Student("秦皇","男");
        Student stu2 = new Student("汉武","男");
        g.getStudents().add(stu1);
        g.getStudents().add(stu2);
        Session session = HibernateUtil.getSession();
        Transaction tx = session.beginTransaction();
        session.save(g);
        session.save(stu1);
        session.save(stu2);
        tx.commit();
        HibernateUtil.closeSession(session);
    }
    
    
    //查询班级学生信息
    public static void show(){
        
        Session session1 = HibernateUtil.getSession();
        Grade grade1 = (Grade) session1.get(Grade.class, 1);//得到java1班
        System.out.println("班级名称为:"+grade1.getGname());
        Set<Student> students = grade1.getStudents();
        for(Student stu:students){
            System.out.println("学生姓名为:"+stu.getSname());
        }
        
    }

}

 

posted on 2018-03-13 21:34  菜鸟乙  阅读(190)  评论(0编辑  收藏  举报