Hibernate的使用举例

来源:互联网 发布:mac安装农行安全控件 编辑:程序博客网 时间:2024/05/01 00:44

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




原创粉丝点击