`

hibernate学习(一) 事例

阅读更多
1.maven 管理依赖 ??
mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="store" //运行

2.javaBean
a)get,set 重构时的健壮性
b)private hibernate可直接访问
c)建表使用标识符 id ,set方法private,让hibernate分配标识符值
d)要无参数构造器(hibernate生成对象)
e)使用运行时代理,构造器修饰符>=package(没有字节码指令时,从持久化类获取数据更有效)
f)bidirectional safety method
    public void addToEvent(Event event) {
        this.getEvents().add(event);
        //event.getParticipants().add(this);
    }


3.映射文件(知道怎么加载(load),存储(store)持久化类
a)hibernate不从web加载,先在classpath查找(hibernate.jar)
b)映射文件的属性才被持久化
c)hibernate映射类型(java类型->数据库类型)有自动检测的功能
d)反射会占用资源,时间
e)连接池(内置(功能少),c3p0,proxool)
f)hbm2ddl create 创建表 (ant的schemaExport可把数据库schema重定向到文件)
g)session-factory 到一个数据库的全局factory
h)hibernate可自动detect 数据库方言
i)自动上下文
<property name="current_session_context_class"><!--与线程绑定 不适用大环境 仅用于prototyping-->
thread
</property>
j)id native (oracle HIBERNATE_SEQUENCE 序列取值)

4.启动和辅助类
a)sessionFactory创建session(代表一个线程操作), factory线程安全,全局变量,只能实例化一次
    private static final SessionFactory sessionFactory;

    static {//静态块,类加载创建一次
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {//获得唯一sessionFactory
        return sessionFactory;
    }
/////////////////////3.5方式-使用初始化private方法(类加载被jvm执行一次)
private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            return new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

b)在配置文件中给SessionFactory名称,hibernate创建后会给它绑定到jndi
(可用jmx容器实例化hibernateService,绑定到jndi)
c)getCurrentSession 第一次调用开始,绑定到线程,事务结束,会话与线程剥离,关闭session



5.关联
a)many2many
        <set name="events" table="PERSON_EVENT" inverse="true"><!--中间表 inverse 在另一端可得到关联信息-->
            <key column="PERSON_ID"/>
            <many-to-many column="EVENT_ID" class="Event"/>
        </set>
aPerson.getEvents().add(anEvent);//没有显示save,hibernate自动检测回写数据(自动脏检查(automatic dirty checking)
1)都是!!处于持久化状态(session) 与前一状态不同(更新,保存),hibernate监视,隐式写sql
2)同步内存,数据库(session结束时执行,清理缓存flushing)
3)session由commit结束(CurrentSessionContext的thread配置决定)
4)托管(detached) 以前被持久化过
session.getTransaction().commit();

b)one2many  (值类型集合--依赖类不重要 没有实体entity)
        <set name="emailAddresses" table="PERSON_EMAIL_ADDR">
            <key column="PERSON_ID"/>
            <element type="string" column="EMAIL_ADDR"/> <!--many element-->
        </set>

c)关联方向(directionality),集合(collection),阶数(multiplicity)

d)many2many inverse="true" 可任意
many2one  many一端 inverse="true" 忽略这一端关联,把这看成另一端的镜像


6.public package protected private

7.http get请求

8.session.save(e); 后获得主键
a)session.createQuery("from Event").list(); //返回全部
b)        aPerson.getEmailAddresses().add(emailAddress);//直接用get方法赋值(HashSet())

9.hql
// If we want to handle it bidirectional and detached, we also need to load this
        // collection with an eager outer-join fetch, this time with Criteria and not HQL:
        Event anEvent = (Event) session
                .createCriteria(Event.class).setFetchMode("participants", FetchMode.JOIN)
                .add( Expression.eq("id", (long)1) )
                .uniqueResult(); // Eager fetch the colleciton so we can use it detached
=======================================
Person aPerson = (Person) session
                .createQuery("select p from Person p left join fetch p.events where p.id = :pid")
                .setParameter("pid", (long)30)
                .uniqueResult(); // Eager fetch the collection so we can use it detached

10.每个请求为一个session  session-per-request  getCurrentSession()自动绑定当前线程

11.auto-commit 自动提交
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics