hibernate详解(二)基本编程

2017-10-30  本文已影响0人  秀逼

hibernate程序的开发流程

简单的测试之前的student类,以及相应的映射文件。看注释即可

package com.iotek.basic.common;

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

import com.iotek.basic.pojo.Student;

public class StudentTest {

    public static void main(String[] args) {
        
        // 创建待操作的Student对象
        Student student = new Student();
        student.setName("zhangsan");
        student.setAddress("beijing");
        student.setGender("male");
        student.setAge(20);
        
        // 创建Configuration对象
        Configuration configuration = new Configuration();
        
        // 读取hibernate.cfg.xml文件
        configuration.configure("hibernate.cfg.xml");
        
        // 创建SessionFactory对象: 过时的方法
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        
        // 创建Session对象,打开数据库连接
        Session session = sessionFactory.openSession();
        
        // 创建事务对象e
        Transaction transaction = null;
        
        // CRUD操作
        try {
            
            // 开启事务
            transaction = session.beginTransaction();
            
            // 保存
            session.save(student);
            
            // 查询
            Student stu = session.get(Student.class, 8L);
            System.out.println(stu);
            
            // 提交事务
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
            
            // 回滚事务
            transaction.rollback();
        } finally {
            
            // 关闭事务
            session.close();
        }
    }
}

上一篇 下一篇

猜你喜欢

热点阅读