• 分享知识-快乐自己:Hibernate框架常用API详解


    1):Configuration配置对象

    Configuration用于加载配置文件。

    1): 调用configure()方法,加载src下的hibernate.cfg.xml文件

        Configuration conf = new Configuration().configure();

    2):如果配置文件不符合默认的加载规则,我们可以用:

        new Configuration().configure(file);  //通过file加载

        new Configuration().configure(path);  //通过路径加载

    3): 通过Configuration对象加载映射文件(不推荐,一般都将*hbm.xml映射文件配置到hibernate.cfg.xml中)

        conf.addClass(User.class);

    规范:1、orm映射文件名称应与实体的简单类名一致;

                2、orm映射文件需要与实体的类在同一包下。

    2):SessionFactory工厂

    SessionFactory相当于javaWeb的连接池,用于管理所有的session

    根据Configuration配置信息创建SessionFactory

    SessionFactory sf = conf.buildSessionFactory();

    SessionFactory是线程安全的,可以是成员变量,多个线程同时访问时,不会出现线程并发的问题。

    3):Session会话

    Session相当于JDBC的Connection会话,通过操作session操作PO对象实现增删改查

    session的api:

    1、save  保存

    2、update  更新

    3、delete  删除

    4、get 通过id查询,如果没有null

         load通过id查询,如果没有抛异常

    5、createQuery("hql")   获得Query对象

    6、createCriteria(Class)  获得Criteria对象

    session是单线程,线程不安全,不能编写成员变量。

    4):Transaction事务

    打开事务: Transaction ts = session.beginTransaction();

    获得事务(已经打开的事务对象):session.getTransaction();

    提交事务:commit();

    回滚事务:rollback();

    5):Query对象

    Qyuery主要用于Hibernate执行hql语句。

    hql语句:hibernate提供的面向对象的查询语句,使用对象(类)和属性进行查询,区分大小写。

    获得Query对象:Query query = session.createQuery("hql")

    方法:

    list():查询所有    List<User> list = query.list();

    uniqueResult():获得一个结果

    setFirstResult(int):分页,开始索引数startIndex

    setMaxResult(int):分页,每页显示的个数pageSize

    6):工具类

    package com.zju.model;
     
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
     
    //工具类
    public class H3Utils {
     
        // 会话工厂,整个程序只有一份
        private static SessionFactory factory;
     
        // 放在静态块里
        static {
            // 1 加载配置文件
            Configuration conf = new Configuration().configure();
            // 2 获得工厂
            factory = conf.buildSessionFactory();
            // 3 关闭虚拟机时,释放SessionFactory
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
     
                @Override
                public void run() {
                    System.out.println("虚拟机关闭,释放资源!");
                    factory.close();
                }
            }));
        }
     
        // 获得一个新的session
        public static Session openSession() {
            return factory.openSession();
        }
        
        //获得当前线程中绑定的session
        public static Session getCurrentSession(){
            return factory.getCurrentSession();
        }
    }
  • 相关阅读:
    perl中的默认变量与Z/map介绍
    perl6中字符串字母编历
    将数字转化为特殊符号的密码
    vue: axios
    vue: alias
    background-size
    问题:当浏览器窗口变化时,内容的大小以及相对位置也要相应变化
    vue移动端适配
    Web 端屏幕适配方案
    vue: register and import
  • 原文地址:https://www.cnblogs.com/mlq2017/p/9821228.html
Copyright © 2020-2023  润新知