Hibernate

作者: 西门无鞋 | 来源:发表于2018-03-22 13:04 被阅读0次

1. 初识Hibernate

基本概念

  • ORM:(object relation mapping)


    ORM示意图1
    ORM示意图2
  • 阻抗不匹配:对象和关系型数据库不匹配
  • 没有侵入性:代码中不用去继承hibernate提供的借口
  • Hibernate是一个ORM轻量级框架;解决持久化操作,使得程序员可以从便携反复的JDBC工作中解放出来,专注于业务。提高程序员的开发效率。Hibernate是一个全功能ORM框架
  • 移植性:方言HQL:hibernate query language。根据配置转换成对应数据库的sql。

配置文件:

  • hibernate.cfg.xml:主配置文件,跟数据库打交道,
  • *.hbm.xml:和对象匹配

2. 入门demo

  • hibernate.cfg.xml
<hibernate-configuration>
    <session-factory>
        <!-- 配置数据库连接信息 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <!-- 数据库方言 --><!-- hibernate4以上可以直接使用MySQL5Dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
    </session-factory>
</hibernate-configuration>

  • 建库和pojo对象
public class User {
    private Integer id;
    private String name;
    private String pwd;
}
  • 编写*.hbm.xml
<hibernate-mapping>
    <class name="com.yxxy.pojo.User" table="user">
        <id>
            <!-- 主键生成策略 -->
            <generator class="native"></generator>
        </id>
        <!-- 实体类的属性 -->
        <property name="name"></property>
        <property name="pwd"></property>
    </class>
</hibernate-mapping>
  • 添加该hbm.xml到hibernate.cfg.xml中
<mapping resource="com/yxxy/pojo/User.hbm.xml"/>
  • 测试功能
public class HibernateTest {

    public static void main(String[] args) {
        // 1、新建Configuration对象
        Configuration cfg = new Configuration().configure();
        // 2、通过Configuration对象创建SessionFactory
            //在hibernate3.x中是这样写
            //SessionFactory sf = cfg.buildSessionFactory();
        // hibernate4.3
        ServiceRegistry sr = new StandardServiceRegistryBuilder()
                                    .applySettings(cfg.getProperties()).build();
        SessionFactory sf = cfg.buildSessionFactory(sr);
        // 3、通过SessionFactory得到Session
        Session session = sf.openSession();
        // 4、通过Session对象得到Transaction对象
        Transaction tx = session.beginTransaction();
        // 5、保存数据
        User user = new User();
        user.setName("张三");
        user.setPwd("111");
        session.save(user);
        // 6、提交事务
        tx.commit();
        // 7、关闭session
        session.close();
    }
    
}

3. Hibernate详解

  • Configuration管理读取配置文件
        // 1、新建Configuration对象
        Configuration cfg = new Configuration().configure();
            // 读取src下hibernate.properties,不推荐使用
            //Configuration cfg1 = new Configuration();
            // 默认读取是src下的hibernate.cfg.xml
            // 如果hibernate的核心配置文件不叫hibernate.cfg.xml
            // Configuration cfg2 = new Configuration().configure("hb.cfg.xml");
            // 可编程式,不需要配置文件
            // cfg2.addProperties(extraProperties);
            // cfg2.addResource(resourceName);

  • SessionFactory对象
// 2、通过Configuration对象创建SessionFactory
            //在hibernate3.x中是这样写
            //SessionFactory sf = cfg.buildSessionFactory();
        // hibernate4.3
        ServiceRegistry sr = new StandardServiceRegistryBuilder()
                                    .applySettings(cfg.getProperties()).build();
        SessionFactory sf = cfg.buildSessionFactory(sr);

  • Session对象
    Hibernate对数据库crud操作,主要使用session。Session可以理解为对Connection对象的一个包装。Session是一个线程不安全的对象,生命周期非常短暂,一般和事务一一对应。使用完马上关闭就是为了放置线程不安全问题。Session又成为hibernate的一级缓存。
  • Transaction对象
    事务管理对象,通过session来获取该对象。
        // 第一种
        Transaction tx = session.beginTransaction();
        // 第二种
        Transaction getTx = session.getTransaction();
        getTx.begin();
  • 事务和异常处理
public class TestException {
    
    public static void main(String[] args) {
        Configuration cfg = null;
        SessionFactory sf = null;
        Session session = null;
        Transaction tx = null;
        try {
            // 1、新建Configuration对象
            cfg = new Configuration().configure();
            // 2、通过Configuration对象创建SessionFactory
            ServiceRegistry sr = new StandardServiceRegistryBuilder()
                                        .applySettings(cfg.getProperties()).build();
            sf = cfg.buildSessionFactory(sr);
            // 3、通过SessionFactory得到Session
            session = sf.openSession();
            // 4、通过Session对象得到Transaction对象
            tx = session.beginTransaction();
            // 5、操作数据
            User u = (User) session.get(User.class, 2);
            System.out.println(u);
            // 6、提交事务
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            // 回滚事务
            tx.rollback();
        } finally {
            // 7、关闭session
            if(session != null && session.isOpen())
                session.close();
        }
    }
    
}
  • Query对象--后续再说

4. Hibernate log和配置文件详解

  • log
    确定要使用日志的实现——log4j


    log4j的jar包

    编写log4j.properties

  • hibernate.cfg.xml讲解
<hibernate-configuration>
    <session-factory>
        <!-- 配置数据库连接信息 -->
        <!-- 数据库驱动 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <!-- hibernate可选项信息 -->
        <!-- 数据库方言 --><!-- hibernate4以上可以直接使用MySQL5Dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- 是否打印sql语句 -->
        <property name="show_sql">true</property>
        <!-- 格式化sql语句 -->
        <property name="format_sql">true</property>
        <!-- 
            数据库更新方式
                create:每次执行都先把原有数据表删除,然后创建该表
                create-drop:关闭SessionFactory时,将删除掉数据库表
                validate:检测
                update:如果表不存在则直接创建表,有就不用创建
         -->
        <property name="hbm2ddl.auto">update</property>
        <!-- 映射文件信息 -->
        <mapping resource="com/yxxy/pojo/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
  • *.hbm.xml
<!-- 
    package声明pojo类所在的包,如果不写那么在class中需要指明pojo类所在的包
 -->
<hibernate-mapping package="com.yxxy.pojo">
    <!-- 
        class指一个pojo类
        name表示pojo类名
        table表示pojo类对应数据库中的表名;如果不写默认是类名
     -->
    <class name="User">
        <!-- 
            id表示实体类的标识
            对应数据库表中的主键
            name指实体类的标识属性名
            column表示对应数据库表的列名;如果不写则数据库中列名和属性名一致
            length表示数据库表中对应数据类型的长度,如果不写用默认值
            type表示类型,如果不写hibernate可以找到对应pojo类的属性的类型
         -->
        <id name="id">
            <!-- 
                主键生成策略
                    uuid:UUID被编码为一个32位16进制数字的字符串
                    native:根据底层数据库的能力选择identity、sequence、hilo中的一个去自增
                    assigned:自己指定主键
             -->
            <generator class="native"></generator>
        </id>
        <!-- 
            实体类的属性
            name:指pojo类属性名称(区分大小写)
            column:两种写法效果一致
         -->
        <property name="name" column="name"></property>
        <property name="pwd">
            <column name="pwd"></column>
        </property>
    </class>
</hibernate-mapping>

相关文章

网友评论

      本文标题:Hibernate

      本文链接:https://www.haomeiwen.com/subject/tjsnqftx.html