Hibernate的使用举例

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值