hibernate环境配置和使用

一.hibernate简介

      
        Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任。

二.hibernate环境搭建

       1.导入hibernate核心jar包

         需要导入hibernate3.jar和lib/required文件下所有的jar包再加上一个hibernate-jpa-2.0-api-1.0.1.Final.jar即可。如图
       

       2.添加hibernate核心配置文件hibernate.cfg.xml

         
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "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>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>
       <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping resource="com/zhouxiang/model/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
       其中<hibernate-configuration>为配置文件的根,session-factory标签下
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>是数据源的配置分别为驱动、url、用户名、密码                     <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>是配置数据库方言即对哪种数据库操作
        <property name="hibernate.show_sql">true</property>是配置是否打印数据库操作语句
        <property name="hibernate.hbm2ddl.auto">update</property>指定对数据库的默认操作
        <mapping resource="com/zhouxiang/model/User.hbm.xml"/>指定要加载的表与实体间映射关系文件

       3.添加表与实体间映射关系文件 xxx.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.zhouxiang.model">
    <class name="User" polymorphism="explicit">
        <id name="id">
            <generator class="uuid" ></generator>
        </id>
        <property name="name" column="username"></property>
        <property name="password" column="password"></property>
    </class>  
</hibernate-mapping>


三.使用hibernate的7个步骤


       1.第一步:

          创建Configuration读取配置信息
           Configuration cfg = new Configuration().configure();

        2.第二步:

          创建sessionFactory
         SessionFactory factory= cfg.buildSessionFactory();

        3.第三步:打开session

        Session session=factory.openSession();

        4.第四步:开启事务Transaction

        session.getTransaction().begin();

        5.第五步:进行持久化操作,即增删查改等操作

          User user=new User();
         user.setName("aaa");
         user.setPassword("123456");
         session.save(user);

        6.第六步:提交事务

        session.getTransaction().commit();

        7.关闭资源,也就是关闭session

         session.close();
       
       第一步通过创建Configuration对象读取hibernate.cfg.xml配置文件信息,为创建对应的session做准备。第二步根据读取的配置文件信息创建sessionfactory对象。在hibernate.cfg.xml文件中有sessionfactory的配置信息,在sessinofactory中配置了数据源及对数据库操作的一些信息,而sessionfactory根据这些信息去创建相应的session对象。session对象是hibernate操作数据库的一个句柄对象,用来将数据持久化或其他的操作,与HttpSession没有本质联系。总的来说hibernate.cfg.xml配置文件信息主要是在为创建数据持久化过程中使用的对象session对象做描述(配置),只不过在hibernate中又封装了configuration、sessionfactory,configuration用来读取配置文件,sessionfactory作为session工厂对象根据configuration提供的指定配置去创建相应的session,进而通过session对象去完成数据的持久化。

四.实例代码

hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"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>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">123456</property>
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hibernate.hbm2ddl.auto">update</property>
		<mapping resource="com/zhouxiang/model/User.hbm.xml"/>
	</session-factory>
</hibernate-configuration>
User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.zhouxiang.model">
    <class name="User" polymorphism="explicit">
        <id name="id">
            <generator class="uuid" ></generator>
        </id>
        <property name="name" column="username"></property>
        <property name="password" column="password"></property>
    </class>   
</hibernate-mapping>
User类
/**
 * 
 */
package com.zhouxiang.model;

/** 
 * @ClassName: User 
 * @Description: TODO
 * @author zx
 * @date 2014年5月15日 上午10:40:43 
 *  
 */
public class User {
    private String id;
    private String name;
    private String password;
    public User()
    {}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
    
    
}
测试类
/**
 * 
 */
package com.zhouxiang.test;

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

import com.zhouxiang.model.User;

/** 
 * @ClassName: Test1 
 * @Description: TODO
 * @author zx
 * @date 2014年5月16日 上午10:09:55 
 *  
 */
public class Test1 {
	public static void main(String args[])
	{
		SessionFactory factory=null;
		Session session=null;
		try {
			Configuration cfg = new Configuration().configure();
                        factory=cfg.buildSessionFactory();
                        session=factory.openSession();
                        session.getTransaction().begin();
                        User user=new User();
                        user.setName("bbb");
                        user.setPassword("123456");
                        session.save(user);
                        session.getTransaction().commit();
		 } catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		finally
		{
			if(session!=null)
			{
             if(session.isOpen())
             {
            	 session.close(); 
             }
			}
		}
	}
}

五.总结

       其实简而言之hibernate只做了一件事,那就是将对象及对象关系持久化到关系型数据库中,而这种映射关系是直接使用面向对象编程思维来操作数据库,这样使得程序员在编程的过程中只需要关注如何处理对象与对象间的关系,而不需要去考虑对象是如何持久化到数据库中。hibernate使得编程人员在软件开发过程中将更多的精力集中在对象的处理上,简化了数据持久化的过程,加快了开发速度,增强了开发效率,降低了风险。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 36
    评论
配置 Hibernate 的环境需要以下步骤: 1. 下载 Hibernate 的最新版本,并将其解压到本地文件夹中。 2. 在项目中添加 Hibernate 的 jar 包,包括 Hibernate 的核心包和依赖包。 3. 配置 Hibernate 的配置文件,命名为 hibernate.cfg.xml,并将其放在类路径下。 4. 在配置文件中配置数据库连接信息,包括数据库驱动、数据库连接 URL、用户名和密码等。 5. 配置 Hibernate 的映射文件,即将 Java 对象与数据库表进行映射。映射文件的命名为 *.hbm.xml。 6. 在代码中使用 Hibernate API 进行数据库的操作,包括增删改查等。 下面是一个简单的示例: 1. 下载 Hibernate 最新版本,并解压到本地文件夹 C:\hibernate。 2. 创建 Java 项目,并在项目中添加 Hibernate 的 jar 包。 3. 在项目的 src 目录下创建 hibernate.cfg.xml 文件,并配置数据库连接信息: ```xml <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">123456</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> </session-factory> </hibernate-configuration> ``` 4. 在项目的 src 目录下创建 User.hbm.xml 文件,并配置用户表的映射信息: ```xml <hibernate-mapping> <class name="com.example.User" table="user"> <id name="id" type="int"> <generator class="native"/> </id> <property name="name" type="string"/> <property name="age" type="int"/> </class> </hibernate-mapping> ``` 5. 在代码中使用 Hibernate API 进行数据库操作: ```java Configuration cfg = new Configuration().configure(); SessionFactory sf = cfg.buildSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); User user = new User(); user.setName("Tom"); user.setAge(20); session.save(user); tx.commit(); session.close(); sf.close(); ``` 以上就是配置 Hibernate 的基本步骤。需要注意的是,Hibernate 的配置和使用方法还有很多细节,需要根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 36
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值