Hibernaate 详解

hibernate.cfg.xml

连接数据库:
connection.username    数据库的名称。这是我自己的是luwei 
connection.password     数据库的密码     luwei
connection.driver_class   数据库连接驱动 com.mysql.jdbc.Driver
connection.url              数据库连接的URL    jdbc:mysql:///luwei

数据库方言:
dialect            org.hibernate.dialect.MySQL5InnoDBDialect
控制台打印SQL
show_sql      true 
格式化SQL(就是美化SQL)
format_sql   true
自动生成表
hbm2ddl.auto      update  创建后就不会删除已有的行和列
                          create  每次都重新生成一个表
                           create-drop   sessionFactory 关闭后就删除
指定程序需要的对象---关系映射文件
<mapping resource="com/hibernate/helloworld/News.hbm.xml"/>

2:每个类是什么含义?

 Configuration类:

         加载hibernate.cfg.xml文件。负责管理Hibernate的配置信息。  持久化类与数据表的映射关系。

创建Configuration    :  Configuration configuration = new Configuration().configure();

configure()方法的源码:

public Configuration configure() throws HibernateException {
        configure( "/hibernate.cfg.xml" );
        return this;
    }

SessionFactory接口:

 创建ServiceRegistry对象:

//hibernate 的任何配置和服务都需要在该对象中注册后才能有效.
        ServiceRegistry serviceRegistry = 
                new ServiceRegistryBuilder().applySettings(configuration.getProperties())
                                            .buildServiceRegistry();

创建SessionFactory:

 SessionFactory  sessionFactory = configuration.buildSessionFactory(serviceRegistry);

Session:

  Session 是应用程序与数据库之间交互操作的一个单线程对象,是 Hibernate 运作的中心,所有持久化对象必须在 session 的管理下才可以进行持久化操作。

  此对象的生命周期很短。Session 对象有一个一级缓存,显式执行 flush 之前,所有的持久层操作的数据都缓存在 session 对象处。相当于 JDBC 中的 Connection。

创建Session:

Session session = sessionFactory.openSession();

常用方法:

    取得持久化对象的方法   get()   load()

    保存。save()  更新。update()    saveOrUpdate()    删除。delete()

    开启事务:beginTransaction()

    管理session:isOpen()   flush()   clear()    evict()    close()

Transaction(事务)

   代表一次原子操作,它具有数据库事务的概念。所有持久层都应该在事务管理下进行,即使是只读操作。
  创建:

//3. 开启事务
Transaction transaction = session.beginTransaction();

事务常用的方法:

    commit():提交关联的session实例。

    rollback():撤销事务操作。

    wasCommitted():检查事务是否提交。

  

原文地址:https://www.cnblogs.com/bulrush/p/7783229.html