SSM框架整合
spring + springMVC + Mybatis三层框架的整合(以图书的增删改查为例)
- 首先创建Maven项目,开始编写pom文件导入依赖;
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>ssmBuild</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 测试类-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
<!-- 数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!-- 数据库连接池 可以不使用,在当搭建中c3p0出现了问题 没有找到原因 就先不使用 -->
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/mchange-commons-java -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>mchange-commons-java</artifactId>
<version>0.2.19</version>
</dependency>
<!-- servlet jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<!-- spring 框架-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.11.RELEASE</version>
</dependency>
<!-- 懒人插件 : 可以不使用-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<!-- spring-aop 切入 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
</dependencies>
<!--静态资源导出问题 防止导出失败-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
- 在java目录下创建四层:
- com.hao.controller
- com.hao.dao
- com.hao.pojo
- com.hao.service
- mybatis-config.xml(模板):用来配置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">
<!-- MyBatis的全局配置文件 -->
<configuration >
</configuration>
- applicationContext.xml(模板):用于汇集管理各个spring组件
<?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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
</beans>
- Mybatis框架的整合:
- 数据库配置文件 database.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=password
数据库8.0以上链接记得配置时区
- IDEA链接数据库(为了方便 对照数据库来编写代码)
- 在pojo(实体类)层编写对应的实体类Books,尽量与数据库表中的字段名相同
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
// 这里使用了Lombok懒人插件,可以自动生成get、set方法
@Data
@AllArgsConstructor //生成全参构造
@NoArgsConstructor // 生成无参构造
public class Books {
private int bookId;
private String bookName;
private String bookInfo;
}
- 在dao(数据访问)层编写对应的Mapper,BookMapper接口,定义要实现的操作数据库方法
import com.hao.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
// 添加一本书
int addBook(Books books);
// 根据主键删除一本书
int deleteBook(@Param("id") int id);
// 根据主键修改一本书
int updateBook( Books books);
// 根据主键查询一本书
Books queryBook(@Param("id") int id);
// 查询全部书籍
List<Books> queryAllBook();
}
- 根据Mapper接口中写好的方法,编写对应的BookMapper.xml来编写sql语句
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--一个mapper对应一个xml-->
<mapper namespace="com.hao.dao.BookMapper">
<!-- 定义添加方法对应的sql-->
<insert id="addBook" parameterType="Books">
insert into ssm.books (bookId,bookName,bookInfo)
values (#{bookId},#{bookName},#{bookInfo});
</insert>
<!-- 定义根据主键删除方法对应的sql-->
<!-- 参数类型,如果是基本类型,则可以忽略不写-->
<delete id="deleteBook" parameterType="int">
delete from ssm.books where bookId = #{id};
</delete>
<!-- 定义更新方法对应的sql-->
<update id="updateBook" parameterType="Books">
update ssm.books
set bookName=#{bookName},bookInfo=#{bookInfo}
where bookId = #{bookId} ;
</update>
<!-- 定义根据主键查询方法对应的sql-->
<select id="queryBook" resultType="Books">
select * from ssm.books where bookId = #{id};
</select>
<!-- 定义查询全部书籍方法对应的sql-->
<select id="queryAllBook" resultType="Books">
select * from ssm.books;
</select>
</mapper>
- 配置mybaits的核心配置文件
<?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">
<!-- MyBatis的全局配置文件 -->
<configuration >
<!-- 配置数据源交给spring去做-->
<!-- 取别名-->
<typeAliases>
<package name="com.hao.pojo"/>
</typeAliases>
<!-- 扫描mapper-->
<mappers>
<mapper class="com.hao.dao.BookMapper"/>
</mappers>
</configuration>
- 在Service(服务)层编写接口和实现类
import com.hao.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
// 接口的编写
public interface BookService {
// 添加一本书
int addBook(Books books);
// 根据主键删除一本书
int deleteBook(int id);
// 根据主键修改一本书
int updateBook(Books books);
// 根据主键查询一本书
Books queryBook(int id);
// 查询全部书籍
List<Books> queryAllBook();
}
import com.hao.dao.BookMapper;
import com.hao.pojo.Books;
import java.util.List;
// 实现类的编写
public class BookServiceImpl implements BookService {
//调用dao层的操作,设置一个set接口,方便Spring管理
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
// 通过调用dao层的方法来实现
@Override
public int addBook(Books books) {
return bookMapper.addBook(books);
}
@Override
public int deleteBook(int id) {
return bookMapper.deleteBook(id);
}
@Override
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
@Override
public Books queryBook(int id) {
return bookMapper.queryBook(id);
}
@Override
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
- Spring 框架的整合
- 配置Spring 整合Mybatis,编写spring-dao.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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 1. 关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!--<!– 2.连接池 常见:dbcp(半自动化),c3p0(自动化操作:自动化的加载配置文件,并且可以配置到对象中),druid,hikari –>-->
<!-- <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}"/>-->
<!--<!–c3p0连接池私有属性配置–>-->
<!-- <property name="maxPoolSize" value="30"/>-->
<!-- <property name="minPoolSize" value="10"/>-->
<!--<!– 关闭连接后不自动commit–>-->
<!-- <property name="autoCommitOnClose" value="false"/>-->
<!--<!– 获取链接超时时间–>-->
<!-- <property name="checkoutTimeout" value="10000"/>-->
<!--<!– 当获取链接失败重试次数–>-->
<!-- <property name="acquireRetryAttempts" value="2"/>-->
<!-- </bean>-->
<!-- Spring 来管理数据源,不需要在mybatis中配置了 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
<!-- 3.sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 绑定mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4. 配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 要扫描的包-->
<property name="basePackage" value="com.hao.dao"/>
</bean>
</beans>
- spring 整合service层,编写Spring-service.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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 1.扫描service下的包-->
<context:component-scan base-package="com.hao.service"/>
<!--2. 将我们所有的业务类,注入到Spring,可以通过配置,也可以通过注解实现-->
<!-- 由于就一个业务类 就用配置来注入-->
<bean id="BookServiceImpl" class="com.hao.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- 3.声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 4.aop 横切事务支持-->
<!-- 配置事务的类,spring帮你做了-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.hao.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
- SpringMVC 框架的整合
- 为Maven项目添加web框架
- 编写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">
<!-- 1.DispatcherServlet-->
<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:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 2.乱码过滤-->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Session-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
- 配置spring-mvc.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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<?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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置springMVC-->
<!-- 1.开启SpringMVC注解驱动-->
<mvc:annotation-driven/>
<!-- 2.静态资源默认servlet配置过滤-->
<mvc:default-servlet-handler/>
<!-- 3.扫描包web相关的bean controller-->
<context:component-scan base-package="com.hao.controller"/>
<!-- 4.配置jsp 显示ViewResolver视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- 将spring配置文件整合,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: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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 整合各个组件,三层-->
<import resource="spring-dao.xml"/>
<import resource="spring-mvc.xml"/>
<import resource="spring-service.xml"/>
</beans>
- 目前为止配置结束,接下来就是controller和 视图层的编写
例如:
import com.hao.pojo.Books;
import com.hao.service.BookService;
import com.hao.service.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.lang.model.element.NestingKind;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
// 引入service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
@RequestMapping("/all")
public String queryAllBook(Model model){
List<Books> books = bookService.queryAllBook();
model.addAttribute("books",books);
return "allBook";
}
@RequestMapping("/add")
public String addBook(){
return "addBook";
}
@RequestMapping("/addBook")
public String addPaper(Books books) {
bookService.addBook(books);
return "redirect:/book/all";
}
@RequestMapping("/toUpDate")
public String toUpdateBook(int id, Model model){
Books books = bookService.queryBook(id);
model.addAttribute("QBook",books);
return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Books books){
bookService.updateBook(books);
return "redirect:/book/all";
}
@RequestMapping("/delete")
public String deleteBook(int id){
bookService.deleteBook(id);
return "redirect:/book/all";
}
}