hibernate案例 测试代码

时间:2023-02-15 22:29:38

测试staff数据表连接到maeclipse

在staff中插入一行

 package com.hibernate.test;

 import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration; import com.hibernate.DAO.Staff; public class StaffTest
{
public void save()
{
Configuration conf = new Configuration();
//无参数,默认加载Hibenate.cfg.xml,也可以闯入其他配置文件名,进行加载 conf.configure();
/*如果Hibernate.cfg.xml中没有配置某些属性,可以通过conf.setProperty(propertyName, value);来配置
如: conf.setProperty("'hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
*/ SessionFactory factory = conf.buildSessionFactory();
//用于构造Session实力的工厂对象 Session session = factory.openSession();
//构造Session Transaction tran = session.beginTransaction();
//通过Session实例开启事务,得到事务对象 //创建staff实体类对象
try{
Staff staff = new Staff();
staff.setId("8888888");
staff.setName("888888");
staff.setPassword("888888"); //使用session实例的save()方法,传入实体类对象,将staff对象持久化
session.save(staff);
tran.commit();
}catch(Exception e){
tran.rollback();
}finally{
//关闭session
session.close();
}
}
public static void main(String[] args)
{
StaffTest test = new StaffTest();
test.save();
}
}