---
title: "spring配置hibernate的sessionFactory"
author: "badboy_990726"
date: "2010-06-01T16:25:33Z"
tags: ["Hibernate", "JDBC", "MySQL", "Spring", "XML"]
categories: ["企业架构"]
slug: "spring-hibernate-sessionfactory"
draft: false
lastmod: "2010-06-03T11:02:28Z"
id: 681136
url: "https://james-t.iteye.com/blog/681136"
---

之前用spring2+hibernate3+struts2开发了一个彩信发布系统，由于第一次使用此架构，造成applicationContext.xml中的配置非常冗长，而且经常因为更改一个小配置项（例：数据库ip、用户名、密码等）将此文件作修改，这及不利于项目维护，万一粗心造成其他地方变动，会对本来正常的项目造成bug 其实那个项目我最后做了分隔，将applicationContext.xml分隔成好几段，但是我觉得其实对于数据库方面的配置，完全可以通过加载hibernate.cfg.xml配置文件来配置项目的sessionFactory，所以这个新项目我决定使用此方式 这里介绍一下spring加载sessionFactory的这2种方式 1、通过配置dataSource来配置sessionFactory \[b]\[color=darkblue]applicationContext.xml\[/color]\[/b] \[code="java"] org.hibernate.dialect.MySQLDialect true classpath:com/tukechina/mms/pojos \[/code] 2、通过加载hibernate.cfg.xml来配置sessionFactory \[b]\[color=darkblue]applicationContext.xml\[/color]\[/b] \[code="java"] \[/code] \[b]\[color=darkblue]hibernate.cfg.xml\[/color]\[/b] \[code="java"] com.mysql.jdbc.Driver 1234 jdbc:mysql://localhost/goodshool root org.hibernate.dialect.MySQLDialect true 20 5 120 100 120 2 true \[/code] 对于第二种配置方案，找到的资料很少，大多数采用第一种，其实还有一种较好的配置 3、通过配置jdbc.properties文件分离数据库的配置 \[b]\[color=darkblue]jdbc.properties\[/color]\[/b] \[code="java"]Mysqljdbc.driverClassName=com.mysql.jdbc.Driver Mysqljdbc.url=jdbc:mysql://localhost/goodshool Mysqljdbc.username=root Mysqljdbc.password=1234 # second cache statistics hibernate.generate\_statistics=true # Property that determines the Hibernate dialect # (only applied with "applicationContext-hibernate.xml") hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show\_sql=true\[/code] \[b]\[color=darkblue]applicationContext.xml\[/color]\[/b] \[code="java"] ${Mysqljdbc.driverClassName} ${Mysqljdbc.url} ${Mysqljdbc.username} ${Mysqljdbc.password} 5 2 20 600 120 ${hibernate.generate\_statistics} ${hibernate.dialect} ${hibernate.show\_sql} classpath:com/shangx/pojos \[/code]