hibernate——hibernate配置:hibernate入门程序

hibernate是一个基于ORM的持久化框架。它是对jdbc的轻量级封装。 Hibernate是一个开放源代码的对象关系映射框架,她对JDBC进行了非常轻量级的对象封装,使得java程序员可以随心所欲的使用对象编程思维来操纵数据库,hibernate可以应用在任何使用JDBC的场合,既可以在java的客户端程序使用,也可以在Servlet/jsp中的Web应用中使用。最具革命意义的是,hibernate可以在应用的EJB的j2ee架构中取代cmp,完成数据持久化的重任。下面通过一张图来分析Hibernate的运行原理:

                                    

从图可以知道hibernate的六大核心接口,两个主要配置文件,以及他们的直接关系。 
1、Configuration接口 : 负责配置并启动hibernate 
2、SessionFactory接口 : 负责初始化hibernate 
3、Session接口 : 负责持久化对象的CRUD操作 
4、Transaction接口 : 负责事务 

5、Query接口和Criteria接口 : 负责执行各种数据库查询 


hibernate工作原理:
1.通过Configuration config = new Configuration().configure();//读取并解析hibernate.cfg.xml配置文件
2.由hibernate.cfg.xml中的<mapping resource="com/xx/User.hbm.xml"/>读取并解析映射信息
3.通过SessionFactory sf = config.buildSessionFactory();//创建SessionFactory
4.Session session = sf.openSession();//打开Sesssion
5.Transaction tx = session.beginTransaction();//创建并启动事务Transation
6.persistent operate操作数据,持久化操作
7.tx.commit();//提交事务
8.关闭Session

9.关闭SesstionFactory

hibernate.cfg.xml配置文件:
[java] view plain copy
  1. <span style="font-size:14px;"><!DOCTYPE hibernate-configuration PUBLIC    
  2.     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"    
  3.     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">    
  4.     
  5. <hibernate-configuration>    
  6.     <session-factory>    
  7.         <!-- 设置数据库驱动 -->    
  8.         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>    
  9.         <!-- 设置数据库URL -->    
  10.         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>    
  11.         <!-- 数据库用户名 -->    
  12.         <property name="hibernate.connection.username">root</property>    
  13.         <!-- 数据库密码 -->    
  14.         <property name="hibernate.connection.password">123456</property>    
  15.         <!-- 指定对应数据库的方言,hibernate为了更好适配各种关系数据库,针对每种数据库都指定了一个方言dialect -->    
  16.         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>    
  17.       
  18.     <!-- 打印sql语句,方便调试 -->  
  19.         <property name="show_sql">true</property>  
  20.     <!-- 格式化sql语句,排版 -->  
  21.     <property name="foramt_sql">true</property>  
  22.     <!-- 指定hibernate生成数据库表的方式:create每次创建新表,update使用原表 -->  
  23.     <property name="hbm2ddl.auto">update</property>  
  24.     <!-- 使用session.getCurrentSession时需要打开该配置 -->  
  25.     <property name="hibernate.current_session_context_class">true</property>  
  26.   
  27.         <!-- 映射文件 -->    
  28.         <mapping resource="com/pechen/hibernate/User.hbm.xml"/>    
  29.     </session-factory>    
  30. </hibernate-configuration>  </span>  
*.hbm.xml映射文件:
[java] view plain copy
  1. <span style="font-size:14px;"><?xml version="1.0"?>    
  2. <!DOCTYPE hibernate-mapping PUBLIC     
  3.     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">    
  5. <hibernate-mapping>    
  6.     <!--生成默认为user的数据库表-->    
  7.     <class name="com.pechen.hibernate.User">    
  8.         <id name="id">    
  9.             <!-- 算法的核心思想是结合机器的网卡、当地时间、一个随机数来生成GUID -->    
  10.             <generator class="uuid"></generator>    
  11.         </id>    
  12.         <property name="name"></property>    
  13.         <property name="password"></property>    
  14.         <property name="createTime" type="date"></property>    
  15.         <property name="expireTime" type="date"></property>    
  16.     </class>    
  17.         
  18. </hibernate-mapping></span>  


hibernate入门程序

1:创建maven项目,pom.xml中映入hibernate和mysql

<!-- 添加Hibernate依赖 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.6.10.Final</version>
        </dependency>
        
        <!-- mysql数据库的驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        
        
        <!-- 添加Log4J依赖 -->    
    <dependency>    
        <groupId>log4j</groupId>    
        <artifactId>log4j</artifactId>    
        <version>1.2.16</version>    
    </dependency>    
        
    <dependency>    
      <groupId>org.slf4j</groupId>    
      <artifactId>slf4j-api</artifactId>    
      <version>1.6.1</version>    
    </dependency>    
        
    <dependency>    
        <groupId>org.slf4j</groupId>    
        <artifactId>slf4j-nop</artifactId>    
        <version>1.6.4</version>    
    </dependency>    
        
    <!-- 添加javassist -->    
    <dependency>    
        <groupId>javassist</groupId>    
        <artifactId>javassist</artifactId>    
        <version>3.11.0.GA</version>    
    </dependency>    

注意:Hibernate 的前提

以下是一个 Hibernate 应用需要的有关包/库的表格,在安装 Hibernate 应用之前你需要先安装它们。为了安装这些包你必须把来自 /lib 的库文件拷贝到 CLASSPATH ,并按以下说明相应地改变 CLASSPATH 变量。maven项目之间引入。

S.N. 包/库
1 dom4j - XML 解析 www.dom4j.org/
2 Xalan - XSLT 处理器 http://xml.apache.org/xalan-j/
3 Xerces - The Xerces Java 解析器 http://xml.apache.org/xerces-j/
4 cglib -Java 类生成库http://cglib.sourceforge.net/
5 log4j - 日志控制 http://logging.apache.org/log4j
6 Commons - 日志,邮件等 http://jakarta.apache.org/commons
7 SLF4J - 简单日志门面 http://www.slf4j.org
2:实体类的编写
package hibernate_demo.pojo;

import java.util.Date;
/**
 * 持久化一个类
 * @author westbrook
 *
 */
public class User {
	private int id;  
    private Date date;  
    private String title;  
    public Date getDate() {  
        return date;  
    }  
    public int getId() {  
        return id;  
    }  
    public String getTitle() {  
        return title;  
    }  
    public void setDate(Date date) {  
        this.date = date;  
    }  
    public void setId(int id) {  
        this.id = id;  
    }  
    public void setTitle(String title) {  
        this.title = title;  
    }  
}

注意:实体类除了属性需要get set方法外,最好还需要有无参的构造方法,因为映射文件映射到实体类时有用到反射。

3:编写映射文件

<?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" >  
<hibernate-mapping package="hibernate_demo.pojo">  
    <class name="User">
        <id name="id" type="int" column="ID_">  
            <generator class="native" />  
        </id>  
        <property name="date" type="timestamp" column="EVENT_DATE" />  
        <property name="title" type="java.lang.String" column="TITLE" /> 
          
    </class>  
</hibernate-mapping> 

注意:映射文件的名称最好是*.hbm.xml

4:编写Hibernate配置文件 hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   <session-factory>
   <!-- 设置数据库驱动 -->    
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>    
        <!-- 设置数据库URL -->    
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/activitidata</property>    
        <!-- 数据库用户名 -->    
        <property name="hibernate.connection.username">root</property>    
        <!-- 数据库密码 -->    
        <property name="hibernate.connection.password">root</property>    
        <!-- 指定对应数据库的方言,hibernate为了更好适配各种关系数据库,针对每种数据库都指定了一个方言dialect -->    
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>    
      
      
      
      
    <!-- 打印sql语句,方便调试 -->  
        <property name="show_sql">true</property>  
    <!-- 格式化sql语句,排版 -->  
    <property name="foramt_sql">true</property>  
    <!-- 指定hibernate生成数据库表的方式:create每次创建新表,update使用原表 -->  
    <property name="hbm2ddl.auto">create</property>  
    <!-- 使用session.getCurrentSession时需要打开该配置 -->  
    <property name="hibernate.current_session_context_class">true</property>  
    
    
    


   <!-- 列出xml的映射文件 -->
   <mapping resource="hibernate_demo/pojo/User.hbm.xml"/>

</session-factory>
</hibernate-configuration> 

5:测试类

package hibernate_demo;

import java.util.Date;

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

import hibernate_demo.pojo.User;

public class HibernateDemo {

	public static void main(String[] args) {
		//读取并解析hibernate.cfg.xml配置文件
		Configuration configuration = new Configuration().configure();
		//创建SessionFactory,负责初始化hibernate 
		SessionFactory sf = configuration.buildSessionFactory();
		//打开Sesssion,负责持久化对象的CRUD操作 
		Session session = sf.openSession();
		//创建并启动事务Transation
		Transaction tx = session.beginTransaction();
		
		User ser = new User();
		ser.setDate(new Date());
		ser.setTitle("12345678");
		
        int userId = (Integer) session.save(ser);
        tx.commit();
        
        session.close();
		
	}
}

6:运行测试类:

        控制台打印结果:

                        


    

        查看数据库:    

                       

猜你喜欢

转载自blog.csdn.net/weixin_40663800/article/details/80086907