1 前言
本demo是基于SSM框架完成的一个小项目,用于初学者进行基本的框架熟练度练习。源码获取方式在文末,以下是程序运行的几个页面:
2 环境搭建
2.1 基本架构
1. 添加依赖包,可以通过properties统一框架版本
<properties> <springversion>5.0.8.RELEASE</springversion> </properties> 1 2 3 <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- 加入ServletAPI --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- MySQL依赖 start --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- 加入MyBatis 依赖 start --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <!-- 引入Spring(包含SpringMVC) 依赖 start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${springversion}</version> </dependency> <!-- 引用插件依赖:MyBatis整合Spring,如果mybatis版本在3.4及以上版本 mybatis-spring的版本要在1.3以上 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 德鲁伊数据连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency> <!-- pagehelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.6</version> </dependency> <!--处理json--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency> <!--javaee--> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> <!--文件上传下载--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> </dependencies>
如果遇到声明式事务报错,需要添加下面的依赖包
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.1</version> </dependency>
2. 添加spring配置文件
实现8个关键步骤
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--1 配置数据源--> <bean id="db" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/kaikeba0917"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <!--2 创建sqlSessionFactory--> <bean id="fac" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="db"/> <!--指定mybatis的配置文件路径--> <property name="configLocation" value="classpath:mybatis.xml"/> <!--指定mybatis的mapper文件路径--> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!--3 创建sqlSessionTemplate(这个类没有无参构造)--> <bean class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="fac"/> </bean> <!--4 配置事务--> <bean id="mytx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="db"/> </bean> <tx:annotation-driven transaction-manager="mytx"/> <!--5 启用springMVC注解--> <mvc:annotation-driven/> <!--6 配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> <!--7 扫描注解包--> <context:component-scan base-package="com.wangjiawei"/> <!--8 配置静态资源访问--> <mvc:default-servlet-handler/> </beans>
3. 配置web.xml文件,同时加载spring配置文件
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>Archetype Created Web Application</display-name> <!--1 配置前端控制器--> <servlet> <servlet-name>aa</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>aa</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--2 处理post乱码--> <filter> <filter-name>bb</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>bb</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
4. 创建数据表,添加项目包结构,包括实体类等
给dao,service,web(controller)包下使用注解创建对象,给service,web中的属性注入对象
dao:
public interface BooksDao { public List<Books> getAll(); }
@Repository public class BookDaoImpl implements BooksDao { /** 该对象来源于配置文件 * */ @Resource private SqlSessionTemplate sqlSessionTemplate; @Override public List<Books> getAll() { return sqlSessionTemplate.selectList("com.wangjiawei.dao.BooksDao.getAll"); } }
service:
public interface BooksService { public List<Books> getAll(); }
@Service public class BooksServiceImpl implements BooksService { @Resource private BooksDao dao; @Override public List<Books> getAll() { return dao.getAll(); } }
web(controller):
@Controller public class BooksController { @Resource private BooksService booksService; @RequestMapping("/getallbooks") public String getAll(ModelMap map){ List<Books> books = booksService.getAll(); map.addAttribute("booklist", books); return "show"; } }
5. 配置文件代码mybatis.xml 及相应的 BooksMapper.xml
mybatis.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> <!--给类起别名--> <typeAliases> <!-- <typeAlias type="com.wangjiawei.bean.Student" alias="stu"></typeAlias>--> <package name="com.wangjiawei.bean"/> </typeAliases> <!--分页插件--> <plugins> <!-- PageHelper4.1.6 --> <plugin interceptor="com.github.pagehelper.PageHelper"> <property name="dialect" value="mysql"/> </plugin> </plugins> </configuration>
BooksMapper.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.wangjiawei.dao.BooksDao"> <select id="getAll" resultType="books"> select * from books </select> </mapper>
6. 配置controller文件
使用的注解:
@Controller
@RequestMapping
@AutoWired
@Qualifier(“empBiz”)
(同上面的步骤4)
7. 添加service,dao层
使用的注解:
@Service
@AutoWired
(1) dao层省略了实现类
(2) dao 层只定义接口,由小树叶创建dao层对象以及扫描mapper文件
注:当添加了spring-jdbc的jar包后,会自动提交事务
8. 前端测试网页
index.jsp:
<html> <body> <h2>Hello World!</h2> <a href="/getallbooks">getallbooks</a> </body> </html>
show.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <h1>show.jsp</h1> <c:forEach items="${booklist}" var="book"> ${book.bookId}——${book.bookName} </c:forEach> </body> </html>
关于其中的配置文件:
当项目启动时加载web.xml文件,web.xml文件加载spring.xml文件,spring的配置文件又去加载了mybatis的配置文件与mapper文件。
2.2 省略dao实现类
先将上面的dao实现类删掉
使用MapperScannerConfigurer替代SqlSessionTemplate
<!--省略实现类--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.dao"></property> <property name="sqlSessionFactoryBeanName" value="fac"></property> </bean>
注意:此时也可以测试使用属性文件的方式来加载数据源(支持属性文件链接数据源)
2.3 ssm整合mybatis反向生成工具
依赖包:
<dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency>
加载插件:
<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <!--配置文件的路径--> <configurationFile>src/main/resources/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> </configuration> <dependencies> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> </dependencies> </plugin> </plugins> </build>
根据插件中的内容,在resource文件夹下创建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> <!--数据库驱动jar --> <classPathEntry location="F:\develop\maven_repository\mysql\mysql-connector-java\5.1.6\mysql-connector-java-5.1.6.jar" /> <context id="MyBatis" targetRuntime="MyBatis3"> <!--去除注释 --> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--数据库连接 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/kaikeba0917" userId="root" password="root"> </jdbcConnection> <!--生成实体类 指定包名 以及生成的地址 (可以自定义地址,但是路径不存在不会自动创建 使用Maven生成在target目录下,会自动创建) --> <javaModelGenerator targetPackage="com.wangjiawei.bean" targetProject="D:\程序员\开课吧新职课\11SSM\5SSM整合\ssm\src\main\java"> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--生成SQLmapper文件 --> <sqlMapGenerator targetPackage="mapper" targetProject="D:\程序员\开课吧新职课\11SSM\5SSM整合\ssm\src\main\resources"> </sqlMapGenerator> <!--生成Dao文件,生成接口 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.wangjiawei.dao" targetProject="D:\程序员\开课吧新职课\11SSM\5SSM整合\ssm\src\main\java"> </javaClientGenerator> <table tableName="student" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration>
maven类型的web项目加载mybatis-generator插件:
注意:反向生成后,最好把该指令删除,否则不小心点了之后,又会生成一遍代码,尤其是mapper xmi文件中sql语句又会生成一遍,运行时会报错。