JavaEE之SSM框架整合
PS:以下内容根据老师讲课内容进行的梳理
创建四个包
在src下创建四个包:entity、dao、service、controller
资源目录结构
在WebContent下建立文件夹:js, jsp, css, images 等
导入需要的Jar包
spring、aop、mybatis、mybatis-spring、dbcp、mysql驱动、lang、jackson等。以下是所有的包
编写配置文件(5个)
在src下创建以下5个文件
applicationContext.xml
- 管理service层的JavaBean 用扫描的方式
<context:component-scan base-package="com.service"></context:component-scan>
- 管理数据源 配置dbcp
class的路径通过Web App Libraries找到dbcp2包的BasicDataSource,然后Copy Qualified Name
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/数据库名"></property>
<property name="username" value="用户名"></property>
<property name="password" value="密码"></property>
<!-- 连接池配置 如最大连接数等 需要的配 这里没配-->
</bean>
另:给数据库设置密码
① 点击数据库的用户
② 将这两个点进去 修改密码
③ 点击连接属性 将刚才的新密码填进去
即可完成。
- 配置数据库的事务处理
① 通知(transactionManager):注入属性; ref的内容是前面dbcp配置的id名
<bean id="transactinManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
② 开启事务注解
<tx:annotation-driven transaction-manager="transactinManager"></tx:annotation-driven>
③ 管理Mybatis: 数据源、configLocation
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
- mybatis-spring整合:扫描Dao层
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.dao"></property>
</bean>
完整的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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 管理service层的JavaBean -->
<context