1.创建表
Configuration cfg = new Configuration().configure();//读hibernate配置文件
SchemaExport se = new SchemaExport(cfg);//获取创建表的对象
se.create(true, true);//创建表
2.插入数据到数据库
Configuration cfg = new Configuration().configure();//读取Hibernate配置文件
SessionFactory sessionfactory = cfg.buildSessionFactory();//获取会话工厂
Session session = sessionfactory.openSession();//打开会话工厂(获取会话)
Transaction ts = session.beginTransaction();//开启事务
Person person = new Person();//创建对象
person.setName("niam");
person.setAddress("asdfasdf");
person.setAge(12);
session.save(person);//将对象存到会话中
ts.commit();//手动提交事务
session.close();
3.读取数据
Configuration cfg = new Configuration().configure();//读取Hibernate配置文件
SessionFactory sessionfactory = cfg.buildSessionFactory();//获取会话工厂
Session session = sessionfactory.openSession();//打开会话工厂(获取会话)
Person person = (Person)session.get(Person.class, "id");//通过get发送请求会立即发送sql
Person person1 = (Person)session.load(Person.class, "id");//通过load发送请求只有在用到时才会发送sql
System.out.println(person.getName());//得到Person,找到对应的数据
其中读取Hibernate配置文件和获取会话都可以在一个工具类中进行封装,比如:
public class HibernateUtil {
public static SessionFactory sessionFactory;
static{
Configuration cfg = new Configuration().configure();
sessionFactory = cfg.buildSessionFactory();
}
public static Session getHibeSess(){
return sessionFactory.openSession();
}
public static void closeHibeSess(Session session){
session.close();
}
public static SessionFactory getHibeSessFact(){
return sessionFactory;
}
}
session 用完一定要关闭哦。。
session 的Get 和 Load方法的区别
1.在执行Person person = (Person)session.get(Person.class, "id");的时候就会发送sql 语句,但是 Load 不会发送
2.如果没找到对象,get放回空,报NullPointException异常,找到就返回该对象
3.而返回一个Cglib的代理对象load 会报 ObjectNutFoundException异常
Hibernate中实体的三个状态
1.瞬时 new出来
2.持久 放入session 中
3.游离 关闭session