非web工程下 spring+Hibernate整合

  可以利用hibernate的反向生成,將數據庫的表映射爲對象。根據數據庫中的Tstation表,生成station.java和station.hbm.xml文件。在純粹的hibernate訪問中要手動創建sessionFactory的實例,而spring的IoC容器提供了這種管理方式,可以以聲明的方式配置SessionFactory實例,還可以爲SessionFactory注入數據源的引用。所以可以建立bean.xml,用來定義datoSource和sessionFactory

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/dcapparamdb"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
<property name="maxActive" value="100"></property>
<property name="maxIdle" value="30"></property>
<property name="maxWait" value="500"></property>
<property name="defaultAutoCommit" value="true"></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>entity/TDevice.hbm.xml</value>
<value>entity/Tycnew.hbm.xml</value>
<value>entity/TStation.hbm.xml</value>
</list>
</property></bean>
<bean id="ycnewdao" class="entity.TycnewDaoImpl">
<property name="sessionFactory">
<ref bean="sessionFactory"/></property>
</bean>
<bean id="stationdao" class="entity.TStationDaoImpl">
<property name="sessionFactory">
<ref bean="sessionFactory"/></property>
</bean>
</beans>

在應用中可以用如下代碼完成許多基本的操作

ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml");
    private TStationDao stationdao=(TStationDao)ctx.getBean("stationdao");

list=stationdao.getStations();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章