文章目录
SSM整合
1、需求和步骤分析
使用ssm框架完成对 account 表的增删改查操作
步骤
- 准备数据库和表记录
- 创建web项目
- 编写mybatis在ssm环境中可以单独使用
- 编写spring在ssm环境中可以单独使用
- spring整合mybatis
- 编写springMVC在ssm环境中可以单独使用
- spring整合springMVC
2、环境准备
创建数据表
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`money` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
insert into `account`(`id`,`name`,`money`) values (1,'tom',1000),
(2,'jerry',1000);
创建一个maven项目
3、MyBatis在SSM环境中单独使用
3.1、导入相关依赖
<dependencies>
<!--mybatis坐标-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.15</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
3.2、Account实体类
package com.lzy.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Account {
private Integer id;
private String name;
private Double money;
}
3.3、AccountDao接口
public interface AccountDao {
/*查询所有的信息*/
public List<Account> findAll();
}
3.4、AccountDao.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.lzy.dao.AccountDao">
<select id="findAll" resultType="Account">
selct * from account
</select>
</mapper>
要在这里创建对应的xml文件
3.5、MyBatis核心配置文件
Mybatis-config.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>
<!--加载properties-->
<properties resource="jdbc.properties"/>
<!--类型别名配置-->
<typeAliases>
<package name="com.lzy.pojo"/>
</typeAliases>
<!--配置数据源-->
<environments default="mysql">
<!--使用MySQL环境-->
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--加载映射-->
<mappers>
<package name="com.lzy.dao"/>
</mappers>
</configuration>
jdbc.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=xxxxx
3.6、编写MybatisUtils工具类
package com.lzy.utils;
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 java.io.IOException;
import java.io.InputStream;
public class MybaitsUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static{
try {
// 配置文件路径
String resource = "mybaits-config.xml";
// 加载配置文件
InputStream resourceAsStream = Resources.getResourceAsStream(resource);
// 获取到sqlSessionFactory对象
sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
3.6、测试代码
import com.lzy.dao.AccountDao;
import com.lzy.pojo.Account;
import com.lzy.utils.MybaitsUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class test {
@Test
public void test1(){
SqlSession sqlSession = MybaitsUtils.getSqlSession();
AccountDao mapper = sqlSession.getMapper(AccountDao.class);
List<Account> all = mapper.findAll();
for (Account account : all) {
System.out.println(account);
}
sqlSession.close();
}
}
注意
:
- MyBatis的核心配置文件我觉得只要是言简意赅,能一眼看出来这是啥的配置文件就可
- 注意编写Mybaits工具类的时候,一定要注意导对包ibatis
- 核心配置文件中的配置,一定要注意,最好是记住,记不住就整理好,下次直接复制
4、编写spring在ssm环境中可以单独使用
4.1、导入相关依赖
<!--这个webmvc中包含好多的依赖包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
4.2、AccountService接口
public interface AccountService {
public List<Account> findAll();
}
4.3、AccountServiceImpl实现
@Service
public class AccountServiceImpl implements AccountService {
@Override
public List<Account> findAll() {
System.out.println("findAll执行了");
return null;
}
}
注意加上@Service,要不然的不会被spring所管理的
4.4、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"
xmlns:aop="http://www.springframework.org/schema/aop"
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.lzy.service"/>
</beans>
4.5、测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class test {
@Autowired
private AccountService accountService;
@Test
public void testSpring() throws Exception{
List<Account> all = accountService.findAll();
System.out.println(all);
}
}
5、spring整合mybatis
5.1、整合思想
将mybatis接口代理对象的创建权交给spring管理,我们就可以把dao的代理对象注入到service中,此时也就完成了spring与mybatis的整合了。
5.2、导入整合包
<!--mybatis整合spring坐标-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
5.3、spring配置文件管理mybatis
注意:此时可以将mybatis主配置文件删除,那个MybatisUtils的工具类也可以不要了
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
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.lzy.service"/>
<!--spring整合mybaits-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<!--SqlSessionFactory创建交给Spring的IOC容器-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--数据库环境配置-->
<property name="dataSource" ref="dataSource"/>
<!--类型别名配置-->
<property name="typeAliasesPackage" value="com.lzy.pojo"/>
</bean>
<!--映射接口扫描配置,由spring创建代理对象,交给IOC容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lzy.dao"/>
</bean>
</beans>
-
相当于mybaits-config.xml中的读取数据库配置的操作
-
把创建SqlSessionFactory交给了spring管理,这里一个是引用一个dataSource,一个是配置别名,这样我们的pojo就可以写小写了
-
这里是把mybaits-config中那个注册mapper那步放到这里来了
5.4、修改AccountServiceImpl
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
return accountDao.findAll();
}
}
6、编写springMVC在ssm环境中可以单独使用
需求:访问到controller里面的方法查询所有账户,并跳转到list.jsp页面进行列表展示
6.1、导入相关依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
6.2、搞几个jsp页面和文件
6.3、前端控制器DispathcerServlet
在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">
<!--前端控制器-->
<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>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--中文乱码处理-->
<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>
</web-app>
6.4、AccountController和 list.jsp
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAll")
public String findAll(Model model){
List<Account> list = new ArrayList<>();
list.add(new Account(1, "张三", 1000d));
list.add(new Account(2, "李四", 2000d));
model.addAttribute("list", list);
return "list";
}
}
<c:forEach items="${list}" var="account">
<tr>
<td>
<input type="checkbox" name="ids" value="${account.id}">
</td>
<td>${account.id}</td>
<td>${account.name}</td>
<td>${account.money}</td>
<td><a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/account/findById?id=${account.id}">修改</a> <a class="btn btn-default btn-sm" href="">删除</a></td>
</tr>
</c:forEach>
6.5、springMVC核心配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--组件扫描-->
<context:component-scan base-package="com.lzy.controller"/>
<!--mvc注解增强-->
<mvc:annotation-driven/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--实现静态资源映射-->
<mvc:default-servlet-handler/>
</beans>
7、spring整合springMVC
7.1、整合思想
- spring和springMVC其实根本就不用整合,本来就是一家。、
- 但是我们需要做到spring和web容器整合,让web容器启动的时候自动加载spring配置文件,web容器销毁的时候spring的ioc容器也销毁。
7.2、spring和web容器整合
ContextLoaderListener加载【掌握】
可以使用spring-web包中的ContextLoaderListener监听器,可以监听servletContext容器的创建和销毁,来同时创建或销毁IOC容器。
在web.xml中配置
<!--配置spring的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
8、spring配置声明式事务
8.1、spring配置文件加入声明式事务
在applicationContext.xml
<!--事务管理器-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--开启事务注解支持-->
<tx:annotation-driven/>
8.2、add.jsp
<form action="${pageContext.request.contextPath}/account/save" method="post">
<div class="form-group">
<label for="name">姓名:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
</div>
<div class="form-group">
<label for="money">余额:</label>
<input type="text" class="form-control" id="money" name="money" placeholder="请输入余额">
</div>
<div class="form-group" style="text-align: center">
<input class="btn btn-primary" type="submit" value="提交" />
<input class="btn btn-default" type="reset" value="重置" />
<input class="btn btn-default" type="button" onclick="history.go(-1)" value="返回" />
</div>
</form>
8.3、AccountController
@RequestMapping("/save")
public String save(Account account){
accountService.save(account);
return "redirect:/account/findAll";
}
8.4、AccountService接口和实现类
public interface AccountService {
public List<Account> findAll();
public void save(Account account);
}
@Override
public void save(Account account) {
accountDao.save(account);
}
8.5、AccountDao和映射
void save(Account account);
<insert id="save" parameterType="Account">
insert into account (name, money) values (#{name}, #{money})
</insert>
9、修改操作
9.1、数据回显
- AccountController
@RequestMapping("/findById")
public String findById(Integer id, Model model) {
Account account = accountService.findById(id);
model.addAttribute("account", account);
return "update";
}
- AccountService接口和实现类
Account findById(Integer id);
@Override
public Account findById(Integer id) {
return accountDao.findById(id);
}
- AccountDao接口和映射文件
Account findById(Integer id);
<select id="findById" parameterType="int" resultType="Account">
select * from account where id = #{id}
</select>
- update.jsp
<form action="${pageContext.request.contextPath}/account/update" method="post">
<input type="hidden" name="id" value="${account.id}">
<div class="form-group">
<label for="name">姓名:</label>
<input type="text" class="form-control" id="name" name="name" value="${account.name}" placeholder="请输入姓名">
</div>
<div class="form-group">
<label for="money">余额:</label>
<input type="text" class="form-control" id="money" name="money" value="${account.money}" placeholder="请输入余额">
</div>
<div class="form-group" style="text-align: center">
<input class="btn btn-primary" type="submit" value="提交" />
<input class="btn btn-default" type="reset" value="重置" />
<input class="btn btn-default" type="button" onclick="history.go(-1)" value="返回" />
</div>
</form>
9.2、账户更新
- AccountController
@RequestMapping("/update")
public String update(Account account){
accountService.update(account);
return "redirect:/account/findAll";
}
- AccountService接口和实现类
void update(Account account);
@Override
public void update(Account account) {
accountDao.update(account);
}
- AccountDao接口和映射文件
void update(Account account);
<update id="update" parameterType="Account">
update account set name = #{name},money = #{money} where id = #{id}
</update>
9.3、批量删除
- list.jsp
<script>
$('#checkAll').click(function () {
$('input[name="ids"]').prop('checked',$(this).prop('checked'));
})
/*给删除选中按钮绑定点击事件*/
$('#deleteBatchBtn').click(function () {
if(confirm('您确定要删除吗')){
if($('input[name=ids]:checked').length > 0){
/*提交表单*/
$('#deleteBatchForm').submit();
}
}else {
alert('想啥呢,没事瞎操作啥')
}
})
</script>
- AccountController
@RequestMapping("/deleteBatch")
public String deleteBatch(Integer[] ids) {
accountService.deleteBatch(ids);
return "redirect:/account/findAll";
}
- AccountService接口和实现类
void deleteBatch(Integer[] ids);
@Override
public void deleteBatch(Integer[] ids) {
accountDao.deleteBatch(ids);
}
- AccountDao接口和映射文件
void deleteBatch(Integer[] ids);