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
- Hibernate的使用举例
- Hibernate使用举例
- 【Hibernate总结系列】使用举例
- (转)【Hibernate总结系列】使用举例
- (转)【Hibernate总结系列】使用举例
- (转)【Hibernate总结系列】使用举例
- (转)【Hibernate总结系列】使用举例
- diaplaytag的使用举例
- Equal 的使用举例
- SortedList的使用举例
- AutoCompleteTextView的使用举例
- ptrace的使用举例
- ScriptObject的使用举例
- 举例理解Hibernate的三种状态
- hibernate的hq,sql,qbc举例
- iReport的style使用举例
- 逻辑运算符的使用举例
- 简单的CSS使用举例
- The constructor Intent(new View.OnClickListener(){}, Class<ButtonStudyActivity>) is undefined
- Oracle无法登陆解决办法
- ios7 国际化
- Java 开源博客——B3log Solo 0.6.5 正式版发布了!
- java中Date的注意事项,写给自己
- Hibernate的使用举例
- [LeetCode] Remove Duplicates from Sorted Array II
- Which SQL statement is the trump card to the senior software developer
- 反素数
- 生成全排列----离散数学及其应用伪代码实现
- 免费PDF转JPG软件(绿色版),PDF转换器工具,不好使你呼我【捡肥皂】
- uva10012 不是那么简单的,有陷阱!
- Unresolved external __fastcall Vcl::Controls::TControl::SetConstraints referenced from CSPIN.OBJ
- 带您解读SQL Server2008中的TIME数据类型