Hibernate使用引用数据源

本文介绍如何在Hibernate中配置数据源,包括在hibernate.cfg.xml文件中设置连接属性、dialect及事务工厂等,并提供了一个SessionFactory创建实例的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration
    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory name="SessionFactory" >
        <!-- datasource connection properties -->
        <property name="connection.datasource">java:comp/env/jdbc/olympic</property>
        <property name="hibernate.connection.autocommit">true</property>
        <!-- dialect for Microsoft SQL Server -->
        <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
    </session-factory>
</hibernate-configuration>

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中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值