1 SSM框架整合
1.1 准备工作
1 原始方式整合
-
创建数据库与表
-
创建Maven工程
-
导入Maven坐标
- 数据库驱动
- spring cotenxt webmvc tx 等
- aspectjweaver
- javeee-api
- jstl
- mybatis
- mybatis-spring
- 服务器
-
编写实体类
package com.raphuscucullatus.domain; /** * Account实体类 * @author raphus cucullatus * @version 2021/9/26 23:19 * @since JDK8 */ public class Account { /** * 账户id */ private Integer id; /** * 账户名 */ private String name; /** * 账户资金 */ private Double balance; 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; } public Double getBalance() { return balance; } public void setBalance(Double money) { this.balance = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", balance=" + balance + '}'; } }
-
编写Mapper接口
package com.raphuscucullatus.mapper; import com.raphuscucullatus.domain.Account; import java.util.List; /** * 基于MyBatis实现账号数据管理 * @author raphus cucullatus * @version 2021/9/26 23:19 * @since JDK8 */ public interface AccountMapper { /** * 插入一条数据 * @param account 账号 */ void insert(Account account); /** * 查询所有账号信息 * @return 账号信息列表 */ List<Account> selectAll(); }
-
编写Service接口与实现
package com.raphuscucullatus.service; import com.raphuscucullatus.domain.Account; import java.util.List; public interface AccountService { void save(Account account); List<Account> findAll(); }
package com.raphuscucullatus.service.impl; import com.raphuscucullatus.domain.Account; import com.raphuscucullatus.mapper.AccountMapper; import com.raphuscucullatus.service.AccountService; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.springframework.stereotype.Service; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * * @author raphus cucullatus * @version 2021/9/26 23:19 * @since JDK8 */ @Service("accountService") public class AccountServiceImpl implements AccountService { /** * 保存用户信息 * @param account 用户信息 */ @Override public void save(Account account) { try { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class); accountMapper.insert(account); //MyBatis需要手动提交 sqlSession.commit(); sqlSession.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 查询所有用户 * @return 返回用户列表 */ @Override public List<Account> findAll() { try { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class); List<Account> accountList = accountMapper.selectAll(); sqlSession.commit(); sqlSession.close(); return accountList; //MyBatis需要手动提交 } catch (IOException e) { e.printStackTrace(); } return null; } }
-
编写Controller
package com.raphuscucullatus.controller; import com.raphuscucullatus.domain.Account; import com.raphuscucullatus.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import java.util.List; /** * Account控制 * @author raphus cucullatus * @version 2021/9/26 23:19 * @since JDK8 */ @Controller @RequestMapping("/account") public class AccountController { /** * 自动注入 */ @Autowired private AccountService accountService; /** * 保存用户信息 * @param account 表单信息 * @return 响应数据 */ @RequestMapping(value = "/save",produces = "text/html;charset=UTF-8") @ResponseBody public String save(Account account){ accountService.save(account); return "保存成功"; } /** * 查询所有用户 * @param modelAndView 模型与视图 * @return 返回 */ @RequestMapping("/findAll") public ModelAndView findAll(ModelAndView modelAndView){ List<Account> accountList = accountService.findAll(); modelAndView.addObject("accountList",accountList); modelAndView.setViewName("showAccountList"); return modelAndView; } }
-
编写前端页面
-
保存账号
-
<%-- Created by IntelliJ IDEA. User: pw Date: 2021/9/26 Time: 23:49 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <body> <h1>保存账户信息表单</h1> <form action="${pageContext.request.contextPath}/account/save" method="post"> 用户名称<input type="text" name="name"><br/> 账户金额<input type="text" name="balance"><br/> <input type="submit" value="保存"><br/> </form> </body> </html>
-
-
展示账号列表
-
<%-- Created by IntelliJ IDEA. User: pw Date: 2021/9/26 Time: 23:49 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <body> <h1>保存账户信息表单</h1> <form action="${pageContext.request.contextPath}/account/save" method="post"> 用户名称<input type="text" name="name"><br/> 账户金额<input type="text" name="balance"><br/> <input type="submit" value="保存"><br/> </form> </body> </html>
-
-
-
编写相应配置文件
-
Web.xml文件: web.xml
-
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- spring框架 --> <!-- 全局初始化参数,给spring读取配置文件地址 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- spring乱码过滤器 --> <filter> <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- springMVC调度控制器 --> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <!-- 设置springMVC的前端控制器所能处理的请求的请求路径 /所匹配的请求可以是/login或.html或.js或.css方式的请求路径 但是/不能匹配.jsp请求路径的请求 --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- spring框架 --> </web-app>
-
-
Spring配置文件: applicationContext.xml
-
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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.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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd "> <!-- --> <context:component-scan base-package="com.raphuscucullatus"> <!-- 排除controller标签的类 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
-
-
SprngMVC配置文件: spring-mvc.xml
-
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" 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/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <!-- 组件扫描 --> <context:component-scan base-package="com.raphuscucullatus.controller"> </context:component-scan> <!-- 注解驱动 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 内部资源视图解析器 --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/static/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 静态资源访问权限 --> <mvc:default-servlet-handler/> </beans>
-
-
数据库连接信息文件: jdbc.properties
-
jdbc.url=jdbc:mysql://127.0.0.1:3306/test jdbc.userName=root jdbc.userPassword=088.5741 jdbc.driver=com.mysql.cj.jdbc.Driver
-
-
MyBatis核心文件: sqlMapConfig.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> <!-- 加载类路径下的jdbc.properties文件 --> <properties resource="jdbc.properties"/> <typeAliases> <typeAlias type="com.raphuscucullatus.domain.Account" alias="Account"/> <!-- 给指定的包下所有的类取别名(省略包名,不用写全类名) 包扫面时,默认别名为 该类的类名或者该类类名首字母小写 --> <!-- <package name="com.raphuscucullatus.domain"/>--> <!-- <package name="cn.raphuscucullatus.java.web.foundational.bean"/>--> </typeAliases> <!-- environments: 表示多个数据库的配置环境信息 default: 表示默认使用那个环境 一般公司至少有三个环境 dev:开发环境 test:测试环境 pro:生产环境/线上环境 三个环境的数据库配置是不同的,因此要准备不同的配置 在公司做项目的时候,开发阶段连接开发环境的数据库,数据库的配置需要运维或者DBA的同事提供 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.userName}"/> <property name="password" value="${jdbc.userPassword}"/> </dataSource> </environment> </environments> <!-- 指定加载哪些映射配置文件 --> <mappers> <!-- 映射配置文件的路径 开发项目是有多个*.xml文件,因此一般会使用包扫描 --> <package name="com.raphuscucullatus.mapper"></package> <!-- <mapper class="com.raphuscucullatus.mapper.AccountMapper"/>--> </mappers> </configuration>
-
-
MyBatis映射文件: AccountMapper.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.raphuscucullatus.mapper.AccountMapper"> <insert id="insert" parameterType="Account"> insert into ssm_account values(#{id},#{name},#{balance}) </insert> <select id="selectAll" resultType="Account"> select * from ssm_account where 1=1 </select> </mapper>
-
-
日志文件: log4j.xml
-
测试首页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="http://localhost:8080/account/findAll">获取账户列表</a><br/>
<a href="http://localhost:8080/static/saveAccountInfo.jsp">保存用户信息</a><br/>
<script></script>
</body>
</html>
1.2 Spring整合MyBatis
在原始整合方式的基础上改动
applicationContext.xml和mybatis核心配置文件即可,其他配置保持不变
将SqlSessionFactory配置到Spring容器中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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.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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- -->
<context:component-scan base-package="com.raphuscucullatus">
<!-- 排除controller标签的类 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 集成mybatis -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.userName}"/>
<property name="password" value="${jdbc.userPassword}"/>
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!-- mybatis核心配置 -->
<property name="configLocation" value="classpath:mybatis-spring.xml"/>
</bean>
<!--
配置mapper包扫描: 扫描到即生成实现类到spring容器中
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.raphuscucullatus.mapper"/>
</bean>
<!-- 集成mybatis -->
<!-- 事务 -->
<!--平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"></property>
</bean>
<!--增强-->
<tx:advice id="advice">
<tx:attributes>
<!--所用方法使用默认事务属性-->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!--织入-->
<aop:config>
<aop:advisor advice-ref="advice" pointcut="execution(* com.raphuscucullatus.service.*.*(..))"/>
</aop:config>
<!-- 事务 -->
</beans>
mybatis核心配置文件
只剩下别名和设置两个配置了
<?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>
<!-- <!–-->
<!-- 加载类路径下的jdbc.properties文件-->
<!-- –>-->
<!-- <properties resource="jdbc.properties"/>-->
<settings>
<!-- 驼峰命名 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
<!-- 全局延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<typeAliases>
<typeAlias type="com.raphuscucullatus.domain.Account" alias="Account"/>
<!--
给指定的包下所有的类取别名(省略包名,不用写全类名)
包扫面时,默认别名为 该类的类名或者该类类名首字母小写
-->
<!-- <package name="com.raphuscucullatus.domain"/>-->
<!-- <package name="cn.raphuscucullatus.java.web.foundational.bean"/>-->
</typeAliases>
<!-- <!–-->
<!-- environments: 表示多个数据库的配置环境信息-->
<!-- default: 表示默认使用那个环境-->
<!-- 一般公司至少有三个环境-->
<!-- dev:开发环境-->
<!-- test:测试环境-->
<!-- pro:生产环境/线上环境-->
<!-- 三个环境的数据库配置是不同的,因此要准备不同的配置-->
<!-- 在公司做项目的时候,开发阶段连接开发环境的数据库,数据库的配置需要运维或者DBA的同事提供-->
<!-- –>-->
<!-- <environments default="development">-->
<!-- <environment id="development">-->
<!-- <transactionManager type="JDBC"/>-->
<!-- <dataSource type="POOLED">-->
<!-- <property name="driver" value="${jdbc.driver}"/>-->
<!-- <property name="url" value="${jdbc.url}"/>-->
<!-- <property name="username" value="${jdbc.userName}"/>-->
<!-- <property name="password" value="${jdbc.userPassword}"/>-->
<!-- </dataSource>-->
<!-- </environment>-->
<!-- </environments>-->
<!-- <!–-->
<!-- 指定加载哪些映射配置文件-->
<!-- –>-->
<!-- <mappers>-->
<!-- <!–-->
<!-- 映射配置文件的路径-->
<!-- 开发项目是有多个*.xml文件,因此一般会使用包扫描-->
<!-- –>-->
<!-- <package name="com.raphuscucullatus.mapper"></package>-->
<!-- <!– <mapper class="com.raphuscucullatus.mapper.AccountMapper"/>–>-->
<!-- </mappers>-->
</configuration>
整合后的Controller
package com.raphuscucullatus.controller;
import com.raphuscucullatus.domain.Account;
import com.raphuscucullatus.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
/**
* Account控制
* @author raphus cucullatus
* @version 2021/9/26 23:19
* @since JDK8
*/
@Controller
@RequestMapping("/account")
public class AccountController {
/**
* 自动注入
*/
@Autowired
private AccountService accountService;
/**
* 保存用户信息
* @param account 表单信息
* @return 响应数据
*/
@RequestMapping(value = "/save",produces = "text/html;charset=UTF-8")
@ResponseBody
public String save(Account account){
accountService.save(account);
return "保存成功";
}
/**
* 查询所有用户
* @param modelAndView 模型与视图
* @return 返回
*/
@RequestMapping("/findAll")
public ModelAndView findAll(ModelAndView modelAndView){
List<Account> accountList = accountService.findAll();
modelAndView.addObject("accountList",accountList);
modelAndView.setViewName("showAccountList");
return modelAndView;
}
}
之后在浏览器测试即可
整合前的Controller
package com.raphuscucullatus.service.impl;
import com.raphuscucullatus.domain.Account;
import com.raphuscucullatus.mapper.AccountMapper;
import com.raphuscucullatus.service.AccountService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
*
* @author raphus cucullatus
* @version 2021/9/26 23:19
* @since JDK8
*/
@Service("accountService")
public class AccountServiceImpl implements AccountService {
/**
* 保存用户信息
* @param account 用户信息
*/
@Override
public void save(Account account) {
try {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
accountMapper.insert(account);
//MyBatis需要手动提交
sqlSession.commit();
sqlSession.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 查询所有用户
* @return 返回用户列表
*/
@Override
public List<Account> findAll() {
try {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
List<Account> accountList = accountMapper.selectAll();
sqlSession.commit();
sqlSession.close();
return accountList;
//MyBatis需要手动提交
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}