共计 15279 个字符,预计需要花费 39 分钟才能阅读完成。
1、整合前准备
1.1、创建数据库和表
数据库为:ssm,表为:students
create database ssm;
CREATE TABLE `students` (`sid` int(11) DEFAULT NULL,
`sname` varchar(20) DEFAULT NULL,
`sex` varchar(2) DEFAULT NULL,
`age` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `students` VALUES ('1', '张三', '男', '19'), ('2', '李四', '男', '20'), ('3', '张红', '女', '19'), ('4', '张八', '男', '18'), ('5', '三李', '男', '19'), ('6', '王六', '女', '20'), ('7', '刘红', '女', '18');
1.2、创建新项目
1.2.1、回顾 maven 工程创建
pom 工程:
用在创建父工程或聚合工程,用作 jar 包的版本控制。我们必须指明这个聚合工程的打包方式为 pom。
war 工程:
发布在服务器上的工程,将会打包成 war。我们需要指明这个项目为一个 web 工程。
jar 工程:
用作 jar 包使用,将会把项目打包成 jar。如果我们不去指明项目,默认的就是打包成 jar 工程,我们也可以添加指明打包方式为 jar。
1.2.2、新项目
maven 创建一个 ssm001 项目
1.2.3、导入 jar 包
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<mysql.version>8.0.11</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
<spring.version>5.2.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.3</version>
</dependency>
</dependencies>
1.2.4、创建包结构
1.2.5、创建 javabean
import java.io.Serializable;
public class Students implements Serializable {private int sid;
private String sname;
private String sex;
private int age;
public int getSid() {return sid;
}
public void setSid(int sid) {this.sid = sid;
}
public String getSname() {return sname;
}
public void setSname(String sname) {this.sname = sname;
}
public String getSex() {return sex;
}
public void setSex(String sex) {this.sex = sex;
}
public int getAge() {return age;
}
public void setAge(int age) {this.age = age;
}
@Override
public String toString() {return "Students{" +
"sid=" + sid +
", sname='" + sname + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
1.2.6、创建持久层
// 接口 IStudentsDAO.java
public interface IStudentsDAO {List<Students> findAll();
Students findById(int sid);
int addStudents(Students students);
int updateStudents(Students students);
int deleteStudents(int sid);
int addCount();
List<Students> findByName(String sname);
}
1.2.7、创建业务层
// 接口 IStudentsService.java
public interface IStudentsService {List<Students> findAll();
Students findById(int sid);
int addStudents(Students students);
int updateStudents(Students students);
int deleteStudents(int sid);
int addCount();
List<Students> findByName(String sname);
}
// 实现类 StudentsServiceImpl.java
@Service("studentsServiceImpl")
public class StudentsServiceImpl implements IStudentsService {@Override
public List<Students> findAll() {System.out.println("查询学生的所有信息!");
return null;
}
@Override
public Students findById(int sid) {System.out.println("通过 SID 查询学生的信息!");
return null;
}
@Override
public int addStudents(Students students) {System.out.println("增加学生的信息!");
return 0;
}
@Override
public int updateStudents(Students students) {System.out.println("修改学生的信息!");
return 0;
}
@Override
public int deleteStudents(int sid) {System.out.println("删除学生的信息!");
return 0;
}
@Override
public int addCount() {System.out.println("通过 SID 查询学生的信息!");
return 0;
}
@Override
public List<Students> findByName(String sname) {System.out.println("通过 NAME 查询学生的信息!");
return null;
}
}
1.2.8、创建控制层
@Controller("studentsController")
public class StudentsController {@RequestMapping("/findAll")
public String findAll(){System.out.println("调用到了控制层 -Controller");
return "list";
}
}
2、整合 Spring
2.1、配置 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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启注解的扫描,希望处理 service 和 dao,controller 不需要 Spring 框架去处理 -->
<context:component-scan base-package="com.tyschool.ssm001" >
<!-- 配置哪些注解不扫描 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
</beans>
2.2、测试 spring 框架
2.2.1、创建包
2.2.2、创建测试文件
STest.java
public class STest {@Test
public void test1(){// 加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
// 获取对象
IStudentsService iStudentsService=(IStudentsService) ac.getBean("studentsServiceImpl");
// 调用方法
iStudentsService.findAll();}
}
3、整合 SpringMVC
3.1、前置控制器
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Archetype Created Web Application</display-name>
<!-- 配置 SpringMVC 核心, 前置控制器 DispatcherServlet -->
<servlet>
<servlet-name>SpringMVCDispathcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置初始化参数,用来读取 springmvc.xml 文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 配置 servlet 的对象的创建时间点:应用加载时创建。取值只能是非 0 正整数,表示启动顺序 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 前置控制器,映射所有地址 -->
<servlet-mapping>
<servlet-name>SpringMVCDispathcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置 springMVC 编码过滤器 -->
<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>
<!-- 启动过滤器 -->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!-- 过滤所有请求 -->
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3.2、配置 springmvc.xml
/resource/springmvc.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:mvc="http://www.springframework.org/schema/mvc"
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
">
<!-- 配置扫描器,扫描注解, 只扫描 Controller 注解 -->
<context:component-scan base-package="com.tyschool.ssm001">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器,配置前缀和后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 过滤静态资源 -->
<mvc:resources mapping="/css/" location="/css/**"/>
<mvc:resources mapping="/images/" location="/images/**"/>
<mvc:resources mapping="/js/" location="/js/**"/>
<!-- 开启 springmvc 注解支持 -->
<mvc:annotation-driven/>
</beans>
3.3、配置 view 层
3.3.1、index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> 测试 </title>
</head>
<body>
<a href="findAll"> 查看学生的所有信息 </a>
</body>
</html>
3.3.2、list.jsp
/pages/list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
到了这里
</body>
</html>
4、Spring 整合 SpringMVC
4.1、问题
applicationContext.xml 在前面启动服务的时候并没有被读取,如何才能读取 applicationContext.xml 这个文件呢?
在测试案例(STest.java)中,我们要去读取 applicationContext.xml 文件,而在实际使用过程中(启动 tomcat 服务器时),我们并没有调用到 applicationContext.xml 文件。所有我们要通过监听器方式,让我们的程序去读取 applicationContext.xml 文件
4.2、配置 web.xml
<!-- 配置 spring 监听器,默认只加载 /WEB-INF 目录下的 applicationContext.xml 配置文件 -->
<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>
4.3、修改控制层
StudentsController.java
@Controller("studentsController")
public class StudentsController {@Autowired
@Qualifier(value="studentsServiceImpl")
private IStudentsService iStudentsService;
@RequestMapping("/findAll")
public String findAll(){System.out.println("调用到了控制层 -Controller");
iStudentsService.findAll();
return "list";
}
}
5、MyBatis 整合
5.1、通过注解完成数据库操作
IStudentsDAO.java
public interface IStudentsDAO {@Select("select * from students")
@Results(id="studentsMap",value={@Result(id=true,column = "sid",property = "sid"),
@Result(column = "sname",property = "sname"),
@Result(column = "sex",property = "sex"),
@Result(column = "age",property = "age")
})
List<Students> findAll();
@Select("select * from students where sid=#{sid}")
@ResultMap("studentsMap")
Students findById(int sid);
@Insert("insert into students(sname,sex,age)values(#{sname},#{sex},#{age})")
@SelectKey(keyColumn = "sid",keyProperty="sid",resultType = Integer.class,before = false,statement = {"select last_insert_id()"})
int addStudents(Students students);
@Update("update students set sname=#{sname},sex=#{sex},age=#{age} where sid=#{sid}")
int updateStudents(Students students);
@Delete("delete from students where sid=#{sid}")
int deleteStudents(int sid);
@Select("select count(*) from students")
int addCount();
@Select("select * from students where sname like #{sname}")
List<Students> findByName(String name);
}
5.2、编写配置文件
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>
<properties resource="db.properties"></properties>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<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.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- <mapper class="com.tyschool.ssm001.dao.IStudentsDAO"></mapper>-->
<package name="com.tyschool.ssm001.dao"/>
</mappers>
</configuration>
db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.123:3306/mybatis?serverTimezone=UTC
jdbc.username=root
jdbc.password=Root12345
5.3、编写测试类
STest1.java
public class STest1 {private InputStream in ;
private SqlSessionFactory factory;
private SqlSession session;
private IStudentsDAO iStudentsDAO;
@Test
public void findAll(){List<Students> students = iStudentsDAO.findAll();
for(Students s : students) {System.out.println(s);
}
}
@After// 在测试方法执行完成之后执行
public void destroy() throws Exception{session.close();
in.close();}
@Before// 在测试方法执行之前执行
public void init()throws Exception {//1. 读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2. 创建构建者对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//3. 创建 SqlSession 工厂对象
factory = builder.build(in);
// 获取代理对象
session=factory.openSession();
//4、初始化 userDao
iStudentsDAO=session.getMapper(IStudentsDAO.class);
}
}
6、Spring 整合 Mybatis
6.1、修改配置
applicationContext.xml
<!-- 加入配置文件 db.properties-->
<context:property-placeholder location="classpath:db.properties"/>
<!--spring 整合 mybatis 配置 -->
<!-- 配置连接池,数据源,C3P0-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 数据库基本信息配置 -->
<property name = "driverClass" value = "${jdbc.driver}" />
<property name = "jdbcUrl" value = "${jdbc.url}" />
<property name = "user" value = "${jdbc.username}" />
<property name = "password" value = "${jdbc.password}" />
</bean>
<!-- 配置 sqlSessionFactory 工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置 DAO 所在的包 -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.tyschool.ssm001.dao"/>
</bean>
6.2、修改 dao
IStudentsDAO.java
加上持久层注解
@Repository("iStudentsDAO")
6.3、修改 service
@Autowired
@Qualifier("iStudentsDAO")
private IStudentsDAO iStudentsDAO;
@Override
public List<Students> findAll() {System.out.println("查询学生的所有信息!");
return iStudentsDAO.findAll();}
6.4、修改 controller
@RequestMapping("/findAll")
public String findAll(Model model){List<Students> list=iStudentsService.findAll();
model.addAttribute("list",list);
return "list";
}
6.5、修改 list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> 查看所有用户信息 </title>
</head>
<body>
${list}
</body>
</html>
7、配置事务
7.1、配置事务
applicationContext.xml
引入前缀,在配置
<!-- 配置 Spring 框架声明式事务管理 -->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!-- 配置 AOP 增强 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.tyschool.ssm001.service.impl.*.*(..))"/>
</aop:config>
7.2、启动测试
http://localhost:8080/ssm001/index.jsp