Servlet3.0+hibernate

Servlet3.0+hibernate

首先介绍一下servlet3.0这个字眼并不是一种可怕的技术又出来了,这个新的一个servlet版本,那么它带有注解和插入式的功能,这里只是模糊的介绍一下,具体的需要另外的去分析了。在没有mvc模式实现的框架下,我们同样可以使用hibernate来帮我们很好的实现数据库的持久层的搭建。那么我们需要做什么呢?

         首先和原来一样 以前怎么写servlet现在还是怎么写,我们需要改变的是还一种方式去实现我们的数据层的操作而已。

         第一步 我们需要导入我们的hibernate所需要的架包,这是使用每个框架所必须的第一步。具体需要哪些架包,读者可以自己去网上搜搜,针对不同的情况,所导入的架包是不唯一的。这里就不在多说了。

         第二步 需要编写hibernate的配置文件,这里讲的比较通俗,其实就是配置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 MyEclipseHibernate Tools. -->

<hibernate-configuration>

    <session-factory>

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

       <property name="connection.url">jdbc:sqlserver://localhost:1433;databaseName=BookManageSystem</property>

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

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

       <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>

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

       <mapping resource="com/theone/json/entity/Admin.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

这里使用的数据库时sqlserver 那么对于mysql和oracle等数据库,大家可以查到不同数据库下的,连接信息。

 

配置可hibernate和数据库的连接配置文件接下来我们需要配置hibernate和数据映射关系了

这个是最重要的,很重要的。

         在上面的这段话里 大家可以看到有这么一句话:

         <mapping resource="com/theone/json/entity/Admin.hbm.xml"/>

这里就是配置实体类和数据库的对应的映射关系的。

这个文件的名字可以自己指定的。

这里在贴出我的demo中的简单的映射关系配置

<?xml version="1.0"encoding="utf-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/HibernateMapping DTD 3.0//EN"

"C:/Users/QIUYU/Desktop/hibernate-mapping-3.0.dtd">

<!--

   Mapping file autogenerated by MyEclipse Persistence Tools

-->

<hibernate-mapping package="com.theone.json.entity">

   <class name="BookCategory" table="BookCategory">

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

            <column name="id"/>

            <generator class="assigned"/>

        </id>

        <property name="name"type="java.lang.String">

            <column name="Name"length="20" not-null="true">

                <comment>图书类型名称</comment>

            </column>

        </property>

        <property name="description"type="java.lang.String">

            <column name="Description"length="20" not-null="true">

                <comment>管理员密码</comment>

            </column>

        </property>

   </class>

   <class name="BookInfo" table="BookInfo">

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

          <column name="id"></column>

          <generator class="assigned"></generator>

       </id>

       <property name="bookName"type="java.lang.String">

          <column name="BookName">

              <comment>名称</comment>

          </column>

       </property>

       <property name="bookAnthor"type="java.lang.String">

          <column name="BookAuthor">

              <comment>作者</comment>

          </column>

       </property>

       <property name="press"type="java.lang.String">

          <column name="Press">

              <comment>出版社</comment>

          </column>

       </property>

       <!-- <many-to-one name="bookCategory"class="BookCategory">

          <columnname="BookCategoryId">

              <comment>图书类型</comment>

          </column>

       </many-to-one> -->

       <property name="buyAddress"type="java.lang.String">

          <column name="BuyAddress">

              <comment>购买地址</comment>

          </column>

       </property>

       <property name="introduction"type="java.lang.String">

          <column name="Introduction">

              <comment>简介</comment>

          </column>

       </property>

       <property name="remark"type="java.lang.String">

          <column name="Remark">

              <comment>备注</comment>

          </column>

       </property>

       <property name="originalPrice"type="java.lang.Double">

          <column name="OriginalPrice">

              <comment>原价</comment>

          </column>

       </property>

       <property name="realPrice"type="java.lang.Double">

          <column name="RealPrice">

              <comment>实际价格</comment>

          </column>

       </property>

       <property name="BuyTime"type="java.util.Date">

          <column name="BuyTime">

              <comment>购买时间</comment>

          </column>

       </property>

   </class>

</hibernate-mapping>

在这里面还未涉及到多对多和多对一等稍微复杂的映射关系,这些内容还是需要大家再次的深入的。

配置完成之后,我们需要编写我们的代码建立连接了。

这里我们需要一个建立连接的factory类似工厂类来帮助我们得到hibernate的session

具体的代码如下

package com.theone.json.Factory;

 

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 theThread 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";

         privatestatic final ThreadLocal<Session> threadLocal = newThreadLocal<Session>();

   private  static Configurationconfiguration = 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 sessionfactory

    *

    */

         publicstatic void rebuildSessionFactory() {

                   try{

                            configuration.configure(configFile);

                            sessionFactory= configuration.buildSessionFactory();

                   }catch (Exception e) {

                            System.err

                                               .println("%%%%Error Creating SessionFactory %%%%");

                            e.printStackTrace();

                   }

         }

 

         /**

    *  Close the single hibernatesession 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

    *

    */

         publicstatic org.hibernate.SessionFactory getSessionFactory() {

                   returnsessionFactory;

         }

 

         /**

    *  return session factory

    *

    *     session factory will berebuilded in the next call

    */

         publicstatic void setConfigFile(String configFile) {

                   HibernateSessionFactory.configFile= configFile;

                   sessionFactory= null;

         }

 

         /**

    *  return hibernate configuration

    *

    */

         publicstatic Configuration getConfiguration() {

                   returnconfiguration;

         }

 

}

 

然后我们在使用的时候我们就可以

HibernateSessionFactory.getSession()来获取了 好了到这里 我们就完成了servlet+hibernate的配置了。


你可能感兴趣的:(数据库,Hibernate,session,servlet,sqlserver,generator)