欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate4之session的常用方法(七)

程序员文章站 2022-04-14 09:18:11
...

1.session中常用方法

Hibernate4之session的常用方法(七)

2.代码

@Test
    public void testLoadClass(){
        // Class c=(Class)session.load(Class.class, Long.valueOf(2));
        Class c=(Class)session.load(Class.class, Long.valueOf(1));
        System.out.println(c.getStudents());// 此时调用,可以删除时调用该方法load
    }

    @Test
    public void testGetClass(){
        // Class c=(Class)session.get(Class.class, Long.valueOf(2));
        Class c=(Class)session.get(Class.class, Long.valueOf(1));// 此时调用
        System.out.println(c.getStudents());
    }

    @Test
    public void testUpdateClass(){
        Session session1=sessionFactory.openSession();
        session1.beginTransaction();
        Class c=(Class)session1.get(Class.class, Long.valueOf(1));
        session1.getTransaction().commit(); // 提交事务
        session1.close();

        Session session2=sessionFactory.openSession();
        session2.beginTransaction();
        c.setName("08计算机本科2");
        session2.update(c);
        session2.getTransaction().commit(); // 提交事务
        session2.close();
    }

    @Test
    public void testSaveOrUpdateClass(){
        Session session1=sessionFactory.openSession();
        session1.beginTransaction();
        Class c=(Class)session1.get(Class.class, Long.valueOf(1));
        session1.getTransaction().commit(); // 提交事务
        session1.close();

        Session session2=sessionFactory.openSession();
        session2.beginTransaction();
        c.setName("08计算机本科3");

        Class c2=new Class();
        c2.setName("09计算机本科3");
        session2.saveOrUpdate(c);
        session2.saveOrUpdate(c2);
        session2.getTransaction().commit(); // 提交事务
        session2.close();
    }

    @Test
    public void testMergeClass(){
        Session session1=sessionFactory.openSession();
        session1.beginTransaction();
        Class c=(Class)session1.get(Class.class, Long.valueOf(1));
        session1.getTransaction().commit(); // 提交事务
        session1.close();

        Session session2=sessionFactory.openSession();
        session2.beginTransaction();

        Class c2=(Class)session2.get(Class.class, Long.valueOf(1));
        c.setName("08计算机本科4");

        session2.merge(c);

        session2.getTransaction().commit(); // 提交事务
        session2.close();
    }

    @Test
    public void testDeleteStudent(){
        Student student=(Student)session.load(Student.class, Long.valueOf(1));
        session.delete(student);
    }
相关标签: hibernate4