1 hibernate的认知:
hibernate是一种实现了ORM映射的持久层框架,它通过持久化类、配置文件、映射文件进行持久化操作。它有三个核心的类 Configuration获取数据库配置信息,SessionFactory类用来产生Session,SessionFactory同时是Hibernate的二级缓存,Session是hibernate的核心类,完成增删改查操作;
2 hibernate的POJO:
hibernate的持久化类要符合POJO,pojo是普通的javaBean,一般是私有属性,get/set方法,无参构造方法;
3 hibernate建表:
xml实现ORM映射
<property name="hbm2ddl.auto">update</property>加入在配置文件中,只要发现数据库表和映射不一样,就会建表;执行的语句如下
Configuration cfg=new Configuration().configure(); SchemaExport schema=new SchemaExport(cfg); schema.create(true, true);
注解实现ORM
持久化类需要个的包:ejb3-persistence.jar hibernate-core.jar hibernate-commons-annotations.jar
package com.tem.hib; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Teacher { @Id private Integer tid; private String tname; private String tpwd; public Integer getTid() { return tid; } public void setTid(Integer tid) { this.tid = tid; } public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname; } public String getTpwd() { return tpwd; } public void setTpwd(String tpwd) { this.tpwd = tpwd; } }
创建 AnnotationConfiguration,不再需要Configuration,所需包 hibernate-annotations.jar
Configuration cfg=new AnnotationConfiguration().configure(); SchemaExport schema=new SchemaExport(cfg); schema.create(true, true);
4 JPA是java对象持久化标准API,可以用XML和注解的形式描述持久化ORM映射;
5 hibernate在使用注解的JPA时候,Configuration要用AnnotationConfiguration代替,包括获取SessionFactory时候;在配置文件里<mapping class="com.tem.hib.Teacher" />要用这种形式;
6 SessionFactory是线程安全的,但是Session不是线性安全的,可以通过ThreadLocal来创建Session的本地副本变量,解决不安全问题;
package com.tem.hib; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final ThreadLocal<Session> threadLoacl=new ThreadLocal<Session>(); private static SessionFactory sessionFactory=null; static{ Configuration cfg=new Configuration().configure(); sessionFactory=cfg.buildSessionFactory(); } public static Session openSession(){ Session session=(Session)threadLoacl.get(); if(session==null||!session.isOpen()){ if(sessionFactory==null){ rebuildSessionFactory(); } session=(sessionFactory!=null)?sessionFactory.openSession():null; threadLoacl.set(session); } return session; } public static SessionFactory rebuildSessionFactory(){ Configuration cfg=new Configuration().configure(); sessionFactory=cfg.buildSessionFactory(); return sessionFactory; } public static SessionFactory getSessionFactory(){ return sessionFactory; } public static void closeSession(){ Session session=(Session)threadLoacl.get(); threadLoacl.set(null); if(session!=null){ session.close(); } } }