Sping进阶之Spring和Hibernate的整合

本文详细介绍如何使用Spring ORM模块集成Hibernate,实现数据库操作。包括配置连接池、SessionFactory、HibernateTemplate等步骤,并通过具体代码实例演示了整合过程。

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

一)使用springORM模块,将spring集成hibernate【UserDao】
     Hibernate可以与Spring集成起来,由Spring来配置原hibernate.cfg.xml文件的相关信息
    (1)整合原理
        (A)spring.xml文件中配置原hibernate的hibernate.cfg.xml和hibernate.properties文件的内容
        (B)

    (2)整合步骤
        (A)配置C3P0连接池
  <bean 
id="comboPooledDataSourceID" 
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/spring"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>

        (B)配置SessionFactory
<bean  
id="localSessionFactoryBeanID"
                class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="comboPooledDataSourceID"/>
<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>cn/itcast/javaee/spring/with_hibernate/User.hbm.xml</value>
</list>
</property>
</bean>

        (C)配置HibernateTemplate
<bean id="hibernateTemplateID" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="localSessionFactoryBeanID"/>
</bean>

        (D)配置UserDao
<bean id="userDaoID" class="cn.itcast.javaee.spring.with_hibernate.UserDao">
<property name="ht" ref="hibernateTemplateID"/>
</bean>

        (E)配置Hibernate事务管理器
<bean 
id="hibernateTransactionManagerID"                 class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="localSessionFactoryBeanID"/>
</bean>

        (F)配置事务增强Advice
<tx:advice id="txAdvice" transaction-manager="hibernateTransactionManagerID">
<tx:attributes>
<tx:method name="addUser"/>
</tx:attributes>
</tx:advice>

        (G)配置AOP
<aop:config>
<aop:pointcut id="xxx" expression="execution(public void addUser(*))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="xxx"/>
</aop:config>


     (3)常用HibernateTemplate类的API【users表(id/username/password)】 
(A)HibernateTemplate.save()/delete()/update():增、删、改
(B)HibernateTemplate.get()/load():根据ID查询
 
         (C)HibernateTemplate.find():根据任意条件查询
(D)HibernateTemplate.deleteAll():批删


(E)HibernateTemplate.execute(万能):分页查询多个对象

         (F)HibernateTemplate.execute(万能):查询出一个整型值

下面用代码实例来介绍spring和hibernate的整合:

首先定义一个实体类:User

package com.spring_hibernate.demo;

public class User {

	private Integer id;
	private String name;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	
}

接着写配置映射文件User.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 <hibernate-mapping package="com.spring_hibernate.demo" >
 	<class name="User" table="users">
 		<id name="id" column="id">
 			<generator class="native"></generator>
 		</id>
 		<property name="name" column="name"></property>
 	</class>   
 </hibernate-mapping>

接下来写配置文件applicationContext.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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
			<!-- 配置c3p0数据库连接池 -->
		<bean id="comdatasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
			<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
			<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/example_db"></property>
			<property name="user" value="root"></property>
			<property name="password" value="04010"></property>
			<property name="initialPoolSize" value="30"></property>
			<property name="acquireIncrement" value="5"></property>
		</bean>
		<!-- 配置SessionFactory -->
		<bean id="localSessionFactoryBean" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
			<property name="dataSource" ref="comdatasource"></property>
			<property name="hibernateProperties">
				<props>
					<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
					<prop key="hibernate.show_sql">true</prop>
					<prop key="hibernate.hbm2ddl.auto">update</prop>
					<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
					<prop key="hibernate.cache.use_query_cache">true</prop>
				</props>
			</property>
			<property name="mappingResources">
				<list>
					<value>com/spring_hibernate/demo/User.hbm.xml</value>
				</list>
			</property>
		</bean>
		<!-- 配置HibernateTemplate -->
		<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
			<property name="sessionFactory" ref="localSessionFactoryBean"></property>
		</bean>
		<!-- 配置目标对象 -->
		<bean id="userDao" class="com.spring_hibernate.demo.UserDao">
			<property name="ht" ref="hibernateTemplate"></property>
		</bean>
		<!-- 配置JdbcTemplate -->
		<!-- 配置jdbc事务管理器 -->
		<!-- 配置事务增强 -->
</beans>

接着写UserDao持久层:

package com.spring_hibernate.demo;

import org.springframework.orm.hibernate3.HibernateTemplate;

public class UserDao {

	private HibernateTemplate ht;

	public void setHt(HibernateTemplate ht) {
		this.ht = ht;
	}
	 public void addUser(User user){
		 ht.save(user);
	 }
}

最后写一个测试类:

package com.spring_hibernate.demo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {

	public static void main(String[] args) {
		ApplicationContext ac=new ClassPathXmlApplicationContext(new String[]{"com/spring_hibernate/demo/applicationContext.xml"});
		User user=new User();
		user.setId(14);
		user.setName("晓敏");
		UserDao userDao=(UserDao) ac.getBean("userDao");
		userDao.addUser(user);
	}
}

运行结果:

log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into users (name) values (?)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值