SSM(SpringMVC+Spring+Mybatis)
一、搭建SpringMVC
1、在maven项目中导入spring-webmvc依赖
<!-- springmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.8.RELEASE</version> </dependency>
2、配置web.xml文件,在web.xml文件中添加如下代码
<servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <!-- 将springmvc核心配置文件位置修改到src/main/resources文件下 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
3、配置springmvc核心配置文件,在src/main/resources文件下创建一个springmvc.xml文件
文件名必须与web.xml文件中的<param-value>classpath:springmvc.xml</param-value>名一致
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!--扫描com.blb.controller下的注解 --> <context:component-scan base-package="com.blb.controller" /> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
4、编写测试类
在src/main/java文件下创建com.blb.controller包,在包下创建一个TestController类
package com.blb.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class TestController { //向浏览器返回 @ResponseBody //拦截地址 @RequestMapping("hello") public String test(){ return "hello world"; } }
5、maven配置tomcat和jdk
<build> <finalName>SSM_T</finalName> <plugins> <!-- jdk配置 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <!-- 配置apache提供的tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> </plugin> </plugins> </build>
6、测试,启动maven项目
访问localhost:8080/项目名/hello
页面出现hello world 表示springmvc搭建成功
二、搭建spring
1、导入spring相关依赖 spring-context
<!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.8.RELEASE</version> </dependency>
2、配置spring核心配置文件
在src/main/resources文件下创建一个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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> </beans>
3、测试是否搭建成功
1)、编写一个类,将其注入spring的IOC容器中
User类
package com.blb.entity; public class User { private String id; private String username; private String password; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + "]"; } }
放入IOC容器中
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean class="com.blb.entity.User"/> </beans>
2)、编写测试类测试
@SuppressWarnings("resource") public static void main(String[] args) { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); User user = applicationContext.getBean(User.class); System.out.println(user); }
控制台打印:User [id=null, username=null, password=null]
spring搭建完成
三、springmvc+spring 整合
因为springmvc和spring 都是spring的框架,所以不需要做过多的整合,只需要把spring设置为项目启动时启动
1、在web.xml文件中配置spring监听
<!-- spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
2、在springmvc核心配置文件中启动cglib代理
xmlns:aop="http://www.springframework.org/schema/aop" http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd <!-- 启动cglib代理 --> <aop:aspectj-autoproxy proxy-target-class="true"/>
四、搭建Mybaits
1、导入相关依赖 因为我们要连接数据库,所以不仅仅要导入mybatis的依赖,还要导入mysql的依赖,最后我们还要生成日志文件,所以还要到如log4j的依赖
<!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
2、使用mybatis generator自动生成实体类和映射文件
1)、首先要通过eclipes安装mybatis generator
2)、创建一个mybatis generator文件
3)、配置generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="context1"> <!-- jdbc --> <jdbcConnection connectionURL="???" driverClass="???" password="???" userId="???" /> <!-- targetPackage 是你要生成的包名 --> <!-- targetProject 是你的项目名 --> <!-- 实体类 --> <javaModelGenerator targetPackage="???" targetProject="???" /> <!-- mapper映射文件 --> <sqlMapGenerator targetPackage="???" targetProject="???" /> <!-- mapper接口 --> <javaClientGenerator targetPackage="???" targetProject="???" type="XMLMAPPER" /> <!-- 要生成的表 --> <table tableName="???"> </table> </context> </generatorConfiguration>
4)、运行generator.xml文件,生成实体类和mapper
3、在src/main/resources文件下创建一个mybatis-cfg.xml文件,并配置
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="logImpl" value="LOG4J" /> <!-- 开启驼峰命名法,将数据库中A_B的形式转为aB形式 --> <setting name="mapUnderscoreToCamelCase" value="true" /> </settings> <typeAliases> <!-- <typeAlias type="com.blb.entity.User" alias="user"/> --> <!-- 为整个包下面的实体类取别名,别名与类名相同 --> <package name="com.blb.entity" /> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <!-- 扫描mapper --> <package name="com.blb.mapper"/> </mappers> </configuration>
4、配置log4j日志,在src/main/resources文件下创建一个log4j.xml文件,并配置
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.blb.mapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
五、Mybatis+Spring 整合
1、导入依赖mybatis-spring 依赖 和连接池c3p0依赖
<!-- mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.1</version> </dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
2、修改applicationContext.xml文件,加入如下代码
<!-- mybatis spring --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis-conf.xml" /> <property name="mapperLocations" value="classpath*:com/blb/mapper/*.xml"/> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"> </property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8"> </property> <property name="user" value="root" /> <property name="password" value="root" /> <property name="maxPoolSize" value="20" /> <property name="minPoolSize" value="2" /> <property name="initialPoolSize"> <value>10</value> </property> <property name="maxIdleTime" value="60" /> <property name="idleConnectionTestPeriod" value="60"></property> <property name="acquireIncrement"> <value>5</value> </property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.blb.mapper" /> </bean>
3、将mybatis-cfg.xml文件中的jdbc连接,和扫描mapper的删除,最后mybatis-cfg.xml的内容为
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="logImpl" value="LOG4J" /> <!-- 开启驼峰命名法,将数据库中A_B的形式转为aB形式 --> <setting name="mapUnderscoreToCamelCase" value="true" /> </settings> <typeAliases> <!-- <typeAlias type="com.blb.entity.User" alias="user"/> --> <!-- 为整个包下面的实体类取别名,别名与类名相同 --> <package name="com.blb.entity" /> </typeAliases> </configuration>
六、开启注解式事务
1、在applicationContext.xml文件中配置
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <constructor-arg ref="dataSource" /> </bean> <!-- 开启注解器事务 --> <tx:annotation-driven transaction-manager="transactionManager" />
2、在对数据库操作的方法上面加上@Transactional ,方法必须抛出异常
@Transactional(rollbackFor=Exception.class)