---
title: "Hibernate使用引用数据源"
author: "butnet"
date: "2008-04-04T10:17:55Z"
tags: []
slug: "hibernate"
draft: false
lastmod: "2008-04-04T10:17:55Z"
id: 261640
url: "https://butnet.iteye.com/blog/261640"
---

**一、hibernate引用数据源配置**  
在hibernate.cfg.xml文件中添加如下内容：

&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;!DOCTYPE hibernate-configuration  
    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"  
    "[http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"](http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd%22)&gt;

&lt;hibernate-configuration&gt;  
    &lt;session-factory name="SessionFactory" &gt;  
        &lt;!-- datasource connection properties --&gt;  
        &lt;property name="connection.datasource"&gt;java:comp/env/jdbc/olympic&lt;/property&gt;  
        &lt;property name="hibernate.connection.autocommit"&gt;true&lt;/property&gt;  
        &lt;!-- dialect for Microsoft SQL Server --&gt;  
        &lt;property name="dialect"&gt;org.hibernate.dialect.SQLServerDialect&lt;/property&gt;  
        &lt;property name="hibernate.show\_sql"&gt;true&lt;/property&gt;  
        &lt;property name="hibernate.transaction.factory\_class"&gt;org.hibernate.transaction.JDBCTransactionFactory&lt;/property&gt;  
    &lt;/session-factory&gt;  
&lt;/hibernate-configuration&gt;

datasource对应server.xml中的数据源名称  
**二、创建SessionFactory类**

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

public class OlympicSessionFactory {  
    private static Configuration config=null;  
    private static SessionFactory sf=null;  
    public static Session getSession(){  
        if(sf==null){  
            if(config==null)  
                config=new Configuration().configure();  
            sf=config.buildSessionFactory();  
        }  
        Session s=null;  
        try{  
            s=sf.getCurrentSession();  
        }catch(Exception e){}  
        if(s==null)  
            s=sf.openSession();  
        return s;  
    }  
    public static Transaction getTransaction(){  
        Transaction tr=getSession().getTransaction();  
        if(tr==null)  
            tr=getSession().beginTransaction();  
        if(!tr.isActive())  
            tr.begin();  
        return tr;  
    }  
}   

**三、注意**  
此hibernate的配置文件hibernate.cfg.xml文件存在在src目录下  
将Hibernate的包Hibernate.jar放入到classpath中