Hibernate学习之路(3) 实现实现保存一个实体到数据库

public class Dome1 {

/*
 * 步骤分析:
 *  1,解析配置文件
 *  2,根据配置文件创建SessionFactory
 *  3.根据SessionFactory创建session
 *  4,开启事务
 *  5,执行操作(保存)
 *  6,提交事务
 *  7,释放资源
 */
@Test
public void test1(){
Customer customer = new Customer();
customer.setCustName("aa");
//第1,2,3步要特别注意,根据hibernate版本的不同,写法也不一样,写的时候一定要注意用当前版本的写法,我的版本是5.3.1
//  1,解析配置文件
Configuration cfg = new Configuration().configure();
//指定映射文件的位置:cfg.addResource("entity/Customer.hbm.xml");
//  2,根据配置文件创建SessionFactory
SessionFactory factory= cfg.buildSessionFactory();
//  3.根据SessionFactory创建session
Session session = factory.openSession();
//  4,开启事务
Transaction tx =  session.beginTransaction();
//  5,执行操作(保存)
session.save(customer);
//  6,提交事务
tx.commit();
//  7,释放资源
session.close();
factory.close();
}  

}

猜你喜欢

转载自blog.csdn.net/QEcode/article/details/80930569