4 配置Hibernate

Hibernate MySql连接配置

在Hibernate中,可以配置很多种数据库,例如MySql、Sql Server和Oracle,Hibernate MySql连接配置举例如下

出错“The processing instruction must begin with the name of the target”,看了几遍xml文件的内容也没发现什么特别,在网上搜了搜发现还是个通病,很多人都遇到过这种问题。其原因是

<? xml version = "1.0" encoding = "UTF-8" ?> 的问号和"xml"之间多了个空格,去掉空格后<?xml version = "1.0" encoding = "UTF-8" ?>就ok了。

hibernate.cfg.xml出错:The content of element type "property" must match "(meta*,(column|formula)*   恩,根据我的经验,可能是你的映射文件没有写好的原因,还有就是property标签的相对应属性值的value写的不对!!!!!

这样说吧,假如你在建立一个类,叫Student,包名字叫做com.bjsxt.hibernate.model

你就得建立一个映射文件,名字叫做Student.hbm.xml里面的内容的package属性就是com.bjsxt.hibernate.model



解决;

项目名上右键--〉myeclipse-->add hibernate capabilites -->next-->hibernate config file --> existing -->选择现有工程存在的hibernate配置文件--> next --> 不生成factory class --> end



  • 添加库文件
    • 从www.hibernate.org网站下载Hibernate发布包(如hibernate.jar),从www.mysql.com下载MySQL的JDBC驱动程序jar包,将这两个jar包放在lib目录
    • 将以下jar包拷到lib目录中:asm.jar、cglib-2.1.3.jar、commons-collections-2.1.1.jar、commons-logging-1.0.4.jar、dom4j-1.6.1.jar、ehcache-1.1.jar、jta.jar
    • 在工程的classpath中包含上述库文件

建立持久化类

例如Product.java:

package test;

//持久化类

public class Product 

{





    private int id ;

    private String name ;

    public Product()

   {





   }

    public int getId() 

    {





          return id ;





    }

    public void setId(int id) 

    {





          this.id = id;





    }

    public String getName() 

    {





          return name ;





    }

    public void setName(String name) 

    {





          this.name = name;





    }     

}

编写反映持久化类与数据库表映射关系的Hibernate映射文件

例如Product.hbm.xml:

<?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="test">

      <class name="Product" table="product" catalog="factory">

           <id name="id" column="id" type=" int ">

                  <generator class="native"/>

           </id>

           <property name="name" column="name" type="java.lang.String" length="255" unique="false"/>

      </class>

</hibernate-mapping>

编写Hibernate配置文件

并在配置文件中通过mapping元素加入持久化类与数据库表映射的信息,即通过resource指定上一步建立的映射文件的位置。例如
Hibernate.cfg.xml

<?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">





<hibernate-configuration>

      <session-factory>





            <property name = "connection.driver_class">com.mysql.jdbc.Driver</property>





            <property name = "connection.url">jdbc:mysql://127.0.0.1:3306/factory</property>





            <property name = "connection.username"></property>





            <property name = "connection.password"></property>





            <property name = "dialect">org.hibernate.dialect.MySQLDialect</property>





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





            <property name = "show_sql">true</property>





            <property name = "format_sql">true</property>





            <mapping resource = "Product.hbm.xml"/>





      </session-factory>

</hibernate-configuration>

使用ThreadLocal控制Session

例如:

package
test;





import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.cfg.Configuration;





public class HibernateSessionFactory {

     private static Log log = LogFactory.getLog(HibernateSessionFactory.class);

     

     // Path of configuration file

     private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

     private static String configFile = CONFIG_FILE_LOCATION;





     // Use ThreadLocal to control Session object

     private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

     private static Configuration configuration = new Configuration();

     private static org.hibernate.SessionFactory sessionFactory;





     /**

     * Abstraction: Obtain Session

     */

     public static Session getSession() throws HibernateException {

          Session session = threadLocal.get();





          // Rebulid Session object if there is no session in ThreadLocal

          if (session == null || !session.isOpen()) {

               if (sessionFactory == null) {

                    rebuildSessionFactory();

               }

               // Obtain Session object

               session = (sessionFactory != null) ? sessionFactory.openSession()

                         : null;

               threadLocal.set(session);

          }          

          return session;

     }





     /**

     * Abstract: Build SessionFactory object

     */

     public static void rebuildSessionFactory() {

          try {

               // Initial application using configuration file

               configuration.configure(configFile);

               // Create SessionFactory object according to the configuration

               // Data model can be created in MySQL automatically after execute this method

               sessionFactory = configuration.buildSessionFactory();

          } catch (Exception e) {

               e.printStackTrace();

          }

     }





     /**

     * Abstraction: Close Session object

     */

     public static void closeSession() throws HibernateException

     {

          Session session = (Session) threadLocal.get();

          threadLocal.set(null);

          if (session != null)

          {

               session.close();

          }          

     }

}

在src目录下建立 ehcache.xml文件,内容如下:

<ehcache>

<diskStore path="java.io.tmpdir"/>

<defaultCache

    maxElementsInMemory="10000"

    eternal="false"

    timeToIdleSeconds="10000"

    timeToLiveSeconds="10000"

    overflowToDisk="true"

/>

  <cache  name="com.hour41.hibernate.vo.common.City"

    maxElementsInMemory="10000"

    eternal="false"

    timeToIdleSeconds="10000"

    timeToLiveSeconds="10000"

    overflowToDisk="true"

/>

</ehcache>

  • 使用Session操作数据库
    • 经过上述过程,就可完成Hibernate的配置了,接下来可以编写程序操作数据库。
    • 具体实例:
  • package test;





    import org.hibernate.Session;

    import org.hibernate.Transaction;





    import test.Product;

    import test.HibernateSessionFactory;





    public class Main {

         public static void main(String [] args)

         {

              // Get session

              Session session = HibernateSessionFactory.getSession();

              Transaction tx = null;

              try

              {

                   // Begin transaction

                   tx = session.beginTransaction();

                   

                   // Create a Product object and set its property

                   Product product = new Product();

                   product.setName("Apple");

                  

                   // Save the object

                   session.save(product);

                   // Commin

                   tx.commit();

              }

              catch (Exception e)

              {

                   if (tx != null)

                   {

                        tx.rollback();

                   }

                   try

                   {

                        // Spread the exception

                        throw e;

                   }

                   catch (Exception e2)

                   {

                        e2.printStackTrace();

                   }

              }

              finally

              {

                   // Close the session

                   session.close();

              }

         }

    }

SSH三大框架整合配置详细步骤(2)的更多相关文章

  1. SSH三大框架整合配置详细步骤(3)

    5 配置Spring2.5 5.1 基础配置 1)        导入spring包.下载spring-framework-2.5.6并解压后,在spring-framework-2.5.6" ...

  2. SSH三大框架整合配置详细步骤(1)

    配置Struts2.0 3.1 基础配置 1)引入Struts必需的五个jar包.下载struts-2.1.6-all.zip解压后,struts-2.1.6\lib目录下是struts所有的相关ja ...

  3. SSH三大框架整合配置详解

    首先,三大框架整合,肯定是要导入相当多的jar包,这是不容置疑的!     这里就不一一列举了,直接截图吧:             (1) 基于配置文件的整合:        第一步:我们需要在we ...

  4. Maven SSH三大框架整合的加载流程

    <Maven精品教程视频\day02视频\03ssh配置文件加载过程.avi;> 此课程中讲 SSH三大框架整合的加载流程,还可以,初步接触的朋友可以听一听. < \day02视频\ ...

  5. SSH三大框架整合案例

    SSH三大框架的整合   SSH三个框架的知识点 一.Hibernate框架 1. Hibernate的核心配置文件 1.1 数据库信息.连接池配置 1.2 Hibernate信息 1.3 映射配置 ...

  6. JavaWeb_(SSH)三大框架整合struts+hibernate+spring_Demo

    三大框架整合 一.SSH导包 二.书写Spring 三.书写Struts 四.整合Spring与Struts 五.书写(与整合)Hibernate.引入c3p0连接池并使用hibernate模板 六. ...

  7. 关于ssh三大框架整合的碎碎念

    三大框架整合,无非就是一个导jar包,修改配置文件的过程.完了就没事了. 还是有很多细节性的问题 比如在spring中写applicationContext.xml文件时不提示: 解决方法如下: 如果 ...

  8. 吴裕雄--天生自然JAVA SPRING框架开发学习笔记:SSM(Spring+Spring MVC+MyBatis)框架整合搭建详细步骤

    因为 Spring MVC 是 Spring 框架中的一个子模块,所以 Spring 与 SpringMVC 之间不存在整合的问题.实际上,SSM 框架的整合只涉及 Spring 与 MyBatis ...

  9. SSH三大框架整合步骤

    Struts2:需要整合的第一个框架: 1.创建一个动态web项目 2.导入struts2必须的jar 放到 lib目录下 ,再 build path 添加web工程中 3.配置struts2的核心配 ...

随机推荐

  1. js实现复制粘贴功能

    在项目中使用到复制粘贴功能,虽然网上有很多大牛封装了很多的插件,但是还是想不去使用插件,就像自己来实现这个功能. 另一篇是禁止复制粘贴 前端er怎样操作剪切复制以及禁止复制+破解等 初步想法: 1. ...

  2. js事件默认行为

    事件默认行为: 当一个事件发生的时候浏览器自己默认做的事情 怎么阻止? 当前这个行为是什么事件触发的,然后在这个事件的处理函数中使用 return false; 但是return false 阻止的是 ...

  3. 数据结构( Pyhon 语言描述 ) — — 第2章:集合概览

    集合类型 定义 个或多个其他对象的对象.集合拥有访问对象.插入对象.删除对象.确定集合大小以及遍历或访问集合的对象的操作 分类 根据组织方式进行 线性集合 线性集合按照位置排列其项,除了第一项,每一项 ...

  4. MySQL账户管理和主从同步

    账户管理 在生产环境下操作数据库时,绝对不可以使用root账户连接,而是创建特定的账户,授予这个账户特定 的操作权限,然后连接进行操作,主要的操作就是数据的CRUD(增删改查) MySQL账户体系:根 ...

  5. LeetCode02-两数相加

    ''' 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两个数相加起来,则会返回一个新的链表来表示 ...

  6. 如何将表的行数赋值给变量(MySQL)

    delimiter $$ drop procedure if exists test_at $$ create definer=root@localhost procedure test_at() b ...

  7. Python中input()和raw_input()函数的区别

    问题:在Python2.7中使用 input() 函数会出现 “NameError: Name ”***“ is not defined 的错误 解决: 使用raw_input() 函数,在Pytho ...

  8. HDU-1041-Computer Transformation,大数递推,水过~~

                                                                                  Computer Transformatio ...

  9. JS变量写到HTML页面中并修改变量值(前台处理数据序号问题)

    有时候我们在前台需要对序号进行处理,我们需要将JS变量写到页面中进行显示. 第一种方式:后台处理 第二种方式:JS中定义全局变量,然后进行显示,可以书写一个JS函数对不同的需要进行不同的替换,也就可以 ...

  10. BMP格式,转载

    BMP文件格式,又称为Bitmap(位图)或是DIB(Device-Independent Device,设备无关位图),是Windows系统中广泛使用的图像文件格式.由于它可以不作任何变换地保存图像 ...