`

hibernate01:概念、正向工程、反向工程

 
阅读更多

第一:概念

1.hibernate:是对jdbc的轻量级封装(轻量级的意思是不用加载大量的资源)。hibernate跟struts一样是开源的框架,我们可以直接加入jar包
2.hibernate按照mvc来说是模型层,按照框架来分是数据访问层。数据访问层的技术包括jdbc、hib、ibatise(爱被ts)
3.利用框架这个半成品我们可以根据数据表直接生成类。
4.由表到类是反向工程。
5.由类生成表是正向工程:先写好类和对象关系映射
6.hibernate完成对数据库的crud操作,也就是说hibernate帮我们完成了对象关系映射的部分和对sql的封装(把sql封装成hql语句)。
7.hibernate3.3,第一个方块是注解,第二个是核心包,第三个不选。最下面的两个是说把jar包放在哪个位置。下一步新建,下一步jdbc连接数据库。新建
8.方言是指各个数据库底层的sql语句的差异性。
9.hibernate的配置文件同样在src下,因为也要随着类的加载而加载。
10.session:session是个接口,里面是静态方法。
11.oracle(thin),wugui(这个是配置数据库的连接字符串),chu1,1234,,加入jar,测试时候输入密码。
12.hibernate文件有三个,配置,视图,代码,在配置中找到我要连接的那个字符串,也就是wugui,这时候在hibernate配置文件中就会出现这几个连接数据库的内容
13pojo:是简单的java对象。做数据的封装。
14.对象关系映射中在hibernate核心包中能够找到他的dtd规则。
15.hibernate配置文件中的hbm2ddl:ddl是定义数据(创建、删除、修改)表,里面写的是create是创建,表明每次都重新创建这个表。如果是update表示有表就增加,没有就创建,只是主键加1.
mapping中写一个属性resource资源里写一个类,表明去解析这个表(意思是根据这个表创建类)。
16.加载hib主配置文件。configuration(肯非哥)类(在hibernatesessionfactory中能够找到)的作用是获得加载配置文件的对象,然后用这个对象加载主配置文件。
 获得session工厂就相当于获得了数据源(连接数据库的四个参数),下面我们就可以获得session对象连接数据库了。session就是获得连接
17.hibernate主配置文件中的配置其实给hibernate框架中的属性赋值。看sf这个对象
18:正向过程步骤:1、加jar包、2用myeclipse连接数据库、3写映射文件、4在hibernate写三个语句和对象关系映射文件

19.查询可以不用事务,因为查询对数据库没有影响。
20.get是单条查找,load也是单条查找
21.hibernate_seqence.nextval
22.查询query,criteria
23.分页:setmaxResult:每页有几个,setfirstResult:起始页。默认数据库中的数据的下标是从0开始的
scheam:是当前用户。关注jqueryui。。。注意springmvc跟struts是相同的。ibatise跟hibernate是相同的
--------------
Criteria  c =session.createCriteria(News.class);是查询全部的一种方法,
c.setMaxResults(3);和c.setFirstResult(1);是分页要用的
------------
Hibernate是对JDBC的轻量级对象封装, Hibernate本身是不具备事务处理功能的,Hibernate事务实际上是底层的JDBC事务的封装,或者是JTA事务的封装Hibernate的JDBCTransaction根本就是conn.commit而已,根本毫无神秘可言,
只不过在Hibernate中, Session打开的时候,就会自动conn.setAutoCommit(false),不像一般的JDBC,默认都是true,所以你最后不写 commit也没有关系,
由于Hibernate已经把AutoCommit给关掉了,所以用Hibernate的时候,你在程序中不写Transaction的话,数据库根本就没有反应。

 

----------------------------------------------------------------------

<property name="hibernate.hbm2ddl.auto">     </property>

这个属性标签中有四个参数可以写,这四个参数是对数据库中插入的进行不同的操作,分别为:

(1)create-drop

(2)create

(3)update

(4)validate

下面分别来介绍他们的作用以及对数据库中的影响

(1)<property name="hibernate.hbm2ddl.auto"> create-drop </property>

create-drop:表示在hebarinate初始化时创建表格,程序运行结束的时候会删除相应的表格,在实际项目中不用

(2)<property name="hibernate.hbm2ddl.auto">create</property>

在hibernate初始化时会创建表格,在运行结束之后不删除表格,而是在下一次运行的时候如果有旧的删掉,没有旧的,重新建表格

(3)<property name="hibernate.hbm2ddl.auto">update</property>

只是根据映射文件去和数据库中的表对应起来,如果不一致,就更新表的结构

(4)<property name="hibernate.hbm2ddl.auto">validate</property>

校验映射文件和数据库中的表是不是能对应起来,不能对应报错,实际中常用

注:在使用的时候必须要慎重,我就是在当时学习的时候所设置的属性是validate,所以只要改了数据库名就会抛初始化异常,当时我郁闷了半天都不知道是怎么回事,没有往这方面想,后来才知到balidate是在没有数据库名的时候不让你创建,会抛异常的。

 

第二:带注释的说明

1.实体类

package com.pojo;

public class TestTable {
 private int tid;
 private String tname;
 
 public int getTid() {
  return tid;
 }
 public void setTid(int tid) {
  this.tid = tid;
 }
 public String getTname() {
  return tname;
 }
 public void setTname(String tname) {
  this.tname = tname;
 }

 
 

}

2.映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <!--
         注意:上面的dtd文件是从jar包中的hibernate3.org.hiberante中的hibernate-mapping-3.0.dtd找到的。其中mapping是映射的意思,他是是帮助我们写映射文件的。
                
 注意:当我们的主键生成策略是<generator class="native"></generator>的时候,就会产生下面的sql语句。native是本地的意思,表示根据本地数据表的格式来自动增长,例如oracle,mysql等
 其中hibernate_sequence.nextval 表示序列的意思。由于是oracle数据库,因此产生了这个序列的sql语句,也就是说在我们写增加的时候,hibernate找到我们当前使用的oracle数据库的自动增长方式
 给我们新添加的这条数据一个新的序列号。
 select
        hibernate_sequence.nextval
    from
        dual -->
<hibernate-mapping package="com.pojo">
     <class name="TestTable" table="chu_testtable" >
        <id name="tid" column="tid" type="int">
           <generator class="native"></generator>
        </id>
        <property name="tname" column="tname" type="java.lang.String"> </property>
     </class>
 
</hibernate-mapping>

 

 

3.hibernate主配置文件

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>
<!-- 注意: <property name="hbm2ddl.auto">update</property>表示的意思是根据映射文件去和数据库中的表对应起来,如果不一致,就更新表的结构 ,也就是增加
<property name="hibernate.hbm2ddl.auto">create-drop</property>表示在hebarinate初始化时创建表格,程序运行结束的时候会删除相应的表格,在实际项目中不用
<property name="hbm2ddl.auto">create</property>表示在hibernate初始化时会创建表格,在运行结束之后不删除表格,而是在下一次运行的时候如果有旧的删掉,没有旧的,重新建表格
<property name="hibernate.hbm2ddl.auto">validate</property>表示校验映射文件和数据库中的表是不是能对应起来,不能对应报错,实际中常用
其中hbm2ddl中的hbm指的是映射文件,2是to的意思,ddl是数据定义语言(增删改),其中update是改,create-drop是增、删,create是增。
-->

<!--
注意:上面规定的dtd文件是来源于的hibernate3这个jar包中的org.hibernate-configuration-3.0.dtd,
其中configuration是配置的意思,也就表明这个dtd文件是针对hibernate主配置文件而规定的。
1.<property name="myeclipse.connection.profile">chu</property>是表明这个是配置数据库的连接字符串,其实
就是表明在myeclipse中的数据库中连接的是chu这个名字的,(除了这个名字,我还有一个名字mysql的)
2.<mapping resource="com/pojo/TestTable.hbm.xml"/>表明解析这个映射文件.
注释:<property name="hbm2ddl.auto">create</property>表明每次都会重新创建表,也就是会导致以前的数据没有了。因此当我们正向生成之后就把这句话去掉,或者改成update
<property name="hbm2ddl.auto">update</property>是每次更新表,可以留着
 -->


<session-factory>
 <property name="myeclipse.connection.profile">chu</property>
 <property name="connection.url">
  jdbc:oracle:thin:@localhost:1521:ORCL
 </property>
 <property name="connection.username">chu1</property>
 <property name="connection.password">1234</property>
 <property name="connection.driver_class">
  oracle.jdbc.OracleDriver
 </property>
 <property name="dialect">
  org.hibernate.dialect.Oracle9Dialect
 </property>
     <property name="hbm2ddl.auto">update</property>
  <property name="show_sql">true</property>
  <property name="format_sql">true</property>
<mapping resource="com/pojo/TestTable.hbm.xml"/>
</session-factory>

</hibernate-configuration>

 

 

4.公共的hibernate工厂类

package com;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /**
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses 
     * #resourceAsStream style lookup for its configuration file.
     * The default classpath location of the hibernate config file is
     * in the default package. Use #setConfigFile() to update
     * the location of the configuration file for the current session.  
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
 private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();   
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

 static {
     try {
   configuration.configure(configFile);
   sessionFactory = configuration.buildSessionFactory();
  } catch (Exception e) {
   System.err
     .println("%%%% Error Creating SessionFactory %%%%");
   e.printStackTrace();
  }
    }
    private HibernateSessionFactory() {
    }
 
 /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

  if (session == null || !session.isOpen()) {
   if (sessionFactory == null) {
    rebuildSessionFactory();
   }
   session = (sessionFactory != null) ? sessionFactory.openSession()
     : null;
   threadLocal.set(session);
  }

        return session;
    }

 /**
     *  Rebuild hibernate session factory
     *
     */
 public static void rebuildSessionFactory() {
  try {
   configuration.configure(configFile);
   sessionFactory = configuration.buildSessionFactory();
  } catch (Exception e) {
   System.err
     .println("%%%% Error Creating SessionFactory %%%%");
   e.printStackTrace();
  }
 }

 /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

 /**
     *  return session factory
     *
     */
 public static org.hibernate.SessionFactory getSessionFactory() {
  return sessionFactory;
 }

 /**
     *  return session factory
     *
     * session factory will be rebuilded in the next call
     */
 public static void setConfigFile(String configFile) {
  HibernateSessionFactory.configFile = configFile;
  sessionFactory = null;
 }

 /**
     *  return hibernate configuration
     *
     */
 public static Configuration getConfiguration() {
  return configuration;
 }

}

 

 

5.真正的dao层调用

package com.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.pojo.TestTable;

public class TestDao {
 public static void main(String[] args) {
  // 加载hibernate的配置文件
  //1 创建Configuration对象,在HibernateSessionFactory这个里面可以看到,我们要获得Configuration对象之后才能加载主配置文件
  Configuration cfg = new Configuration();
  //2 加载配置文件
  cfg.configure("/hibernate.cfg.xml");
  //3 获得SessionFactory对象。通过hibernate.cfg.xml文件我们可以看到,主配置文件里面跟标签就是<session-factory>标签,因此加载了主配置文件后就能获得session工厂了。
  SessionFactory sf  =cfg.buildSessionFactory();
  System.out.println("sf="+sf);//输出:org.hibernate.impl.SessionFactoryImpl

  //4通过session工厂 获得session对象  ----相当于jdbc中的Connection对象。
  Session session =sf.openSession();
  //5 开启事务---由于对数据库有影响,因此要开启事务
  Transaction  tr = session.beginTransaction();
  //6 进行crud操作,执行增删改查,这里我们是增加的方法,传入一个实体类对象之后,数据库就能增加一条记录,为什么?
   //答:由于有映射文件。主配置文件在src目录下,当项目部署到tomact服务器的时候就会把主配置文件加载了,而我们的映射文件在主配置文件中已经配置了,
  //此时也就是说在上面的第三步的时候已经把映射文件加载好了,映射文件里写的是实体类和数据表的关系,因此在我们执行save方法的时候就能把这个参数(对象)转化成数据表的列(字段)
  TestTable tt=new TestTable();
  tt.setTid(1);
  tt.setTname("张三");
  session.save(tt);
  //7 事务处理,提交事务,当我们提交事务的时候hibernate框架会向oracle数据库发送一条insert语句。
  tr.commit();
  
  //8 关闭session,为了防止资源的浪费。
  session.close();

 }
}

 

  • a.zip (7.6 MB)
  • 下载次数: 0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics