MVC案例整合Spring和Hibernate

说到整合Spring和Hibernate首先要搞清楚,整合什么?

1、使用Spring的IOC容器来生产Hibernate的SessionFactory对象实例

2、让Hibernate使用Spring的声明式事务

整合步骤

1、先加入Hibernate

2、在加入Spring,整合

新建项目,建立包结构,演示整合

1、导入hibernate的jar包

XML 复制代码
<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-core</artifactId>
	<version>5.2.17.Final</version>
</dependency>

2、新建配置文件

3、生产model类和数据库的表之间的关系映射xml文件

加入Spring

1、导入jar包

XML 复制代码
<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.0.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>5.0.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>5.0.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>5.0.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>5.0.6.RELEASE</version>
		</dependency>
<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.0.6.RELEASE</version>
 </dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>5.0.6.RELEASE</version>
        </dependency>

2、配置Spring,同时也就整合了

补充一点:Hibernate的配置文件可以去掉,它里边的原生的hibernate属性怎么配置呢?

整合就完了吗?不是,我们还要考虑一些问题

web应用中使用Spring框架的时候,Spring的IOC容器的创建时机:应该是在Web应用被载入服务器的时候,就要创建Ioc容器,并且要将Ioc容器放到Web的ServletContext域中!以供Web应用里的类调用!具体应该怎么做呢?看代码!

web.xml

SpringContextListener.java

在真正的web项目中,是不用我们自己去写SpringContextListener这个监听器的,spring已经给我们写好了一个,我们直接在web.xml配置文件中配置就好了!

通过以下utils工具,可以直接获取到Spring的ioc容器,具体内部细节我们可以不关心:

相关推荐
m0_5873830011 小时前
全民健身解决方案软件开发实战:从架构设计到落地指南
java·spring boot·spring·架构·需求分析
wno70411 小时前
Spring Cloud Hystrix服务容错
spring·spring cloud·hystrix
用户274621291728014 小时前
深入 Spring AI ChatClient:从一行代码到 LLM 调用的完整旅程
spring
麻瓜code19 小时前
【Agent】Spring AI RAG 实战:本地向量库 + 云端知识库
java·人工智能·spring
水巷石子20 小时前
学习langChain4j的第二天,体验springBoot中的starter
java·spring boot·学习·spring·langchain4j
ly768920 小时前
Spring Bean生命周期全流程:从BeanDefinition到销毁
java·后端·spring·bean生命周期·beandefinition·初始化回调
计算机学姐21 小时前
基于SpringBoot的旅游系统的设计与实现
java·vue.js·spring boot·后端·spring·java-ee·旅游
大模型码小白21 小时前
【AI大模型】DeepSeek Harness 深度解析:大模型评测框架的架构与实践
java·运维·人工智能·spring·架构·自动化
苏渡苇1 天前
Spring Insight 里上报 Span 为什么用 JDK HttpClient 而不是 RestTemplate
java·后端·spring·spring cloud·springboot·性能监控
卓怡学长1 天前
w157基于springboot北部湾地区助农平台
java·spring boot·spring·maven·intellij-idea