接上一篇:http://blog.csdn.net/qust008/article/details/9625179
在src下创建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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> <mapping class="qust.thb.po.User" /> </session-factory> </hibernate-configuration>
在WEB-INF文件夹下建hibernate-servlet.xml文件,内容如下
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/bao" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:advice id="txadvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(public * qust.thb..*Service.*(..))" id="allServiceMethod" /> <aop:advisor pointcut-ref="allServiceMethod" advice-ref="txadvice" /> </aop:config> </beans>
由于新增了hibernate-servlet.xml文件,web.xml文件内容也要改变,以便于能够读取hibernate-servlet.xml文件,只需增加
<init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/*-servlet.xml</param-value> </init-param>
后台java代码的具体实现就不写了,直接上传源代码
至此,能够连接数据库的框架搭建完成,框架挺简单的,写在这里主要是怕自己以后忘记了。如果不懂的话,请留言