SSM整合

1.基本结构

1.1 数据准备

CREATE TABLE `book` (
  `book_id` int(11) NOT NULL AUTO_INCREMENT,
  `book_name` varchar(20) DEFAULT NULL,
  `book_price` double DEFAULT NULL,
  `book_author` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`book_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book`(book_name,book_price,book_author) VALUES ( 'Java编程思想', '68', 'zhangsan');
INSERT INTO `book`(book_name,book_price,book_author) VALUES ('网页设计', '46', 'lisi');
INSERT INTO `book`(book_name,book_price,book_author) VALUES ('数据库设计', '28', 'wangwu');

1.2 创建项目

创建maven的web项目,资源路径配置为src/main/webapp,在WEB-INF目录下创建目录jsp,用来存放web相关资源。

1.3 依赖

需要导入SSM相关依赖:junit(可选)、mySQL驱动、mybatis、webmvc、mybatis-spring、spring-jdbc、aspectjweaver、jsp-api、servlet-api、jstl、standard、log4j(可选)。

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>

    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.4.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.4.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.6.8</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.4</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
    </dependency>
</dependencies>

1.4 实体类

创建包com.blb.ssm.bean,定义实体类

public class Book {
	
	private Integer bookId ;
	
	private String bookName  ;
	
	private Double bookPrice 	;
	
	private String bookAuthor  ;
 	
    // setter and getter and toString
}

1.5 控制层

创建包com.blb.ssm.control后,新建控制层类BookController

1.6 DAO层

创建包com.blb.ssm.dao后,新建控制层接口BookMapper。

public interface BookMapper {
	
	public int addBook(Book book);
	
	public int updateBook(Book book);
	
	public int deleteBook(int bookId);
	
	public List<Book> selectBooks();
	
	public Book selectBookById(int bookId);
}

1.7 服务层

创建服务层包com.blb.ssm.service后,新建控制层接口BookService。

public interface BookService {
	
	public int addBook(Book book);
	
	public int updateBook(Book book);
	
	public int deleteBook(int bookId);
	
	public List<Book> selectBooks();
	
	public Book selectBookById(int bookId);

}

创建服务层接口实现类BookServiceImpl

public class BookServiceImpl implements BookService{
	
	@Autowired
	private BookMapper bookMapper ;

	@Override
	public int addBook(Book book) {
		return bookMapper.addBook(book);
	}

	@Override
	public int updateBook(Book book) {
		return bookMapper.updateBook(book);
	}

	@Override
	public int deleteBook(int bookId) {
		return bookMapper.deleteBook(bookId);
	}

	@Override
	public List<Book> selectBooks() {
		return bookMapper.selectBooks();
	}

	@Override
	public Book selectBookById(int bookId) {
		return bookMapper.selectBookById(bookId);
	}

}  

1.8 配置文件

在resources目录下配置相关文件。

数据库连接属性文件database.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis0-db?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root

新建4个Spring的配置文件spring-control.xml、spring-service.xml、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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


</beans>

创建applicationContext.xml,将上面的3个配置文件导入进来

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	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">

	<import resource="spring-control.xml"/>
	<import resource="spring-service.xml"/>
	<import resource="spring-dao.xml"/>

</beans>

创建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>


</configuration>

2、Spring+mybaits

2.1 mapper.xml

在resources目录下创建包com.blb.ssm.dao,并创建mapper对应的配置文件BookMapper.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.blb.ssm.dao.BookMapper">

	<select id="selectBooks" resultType="book">
		select * from book
	</select>

	<insert id="addBook" parameterType="book" >
		insert into book(book_name,book_price,book_author) values (#{bookName},#{bookPrice},#{bookAuthor});
	</insert>

</mapper>

2.2 mybatis-config.xml

增加setting属性跟typeAliases标签

<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
    <setting name="logImpl" value="LOG4J"/>
</settings>

<typeAliases>
    <package name="com.blb.ssm.bean"/>
</typeAliases>

2.3 spring-dao.xml

2.3.1 加载属性配置文件
<context:property-placeholder location="classpath:database.properties"/>
2.3.2 定义数据源

如果需要更换数据源只需要导入依赖,修改class属性值跟property标签。

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driver}"/>
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
</bean>
2.3.3 定义SqlSessionFactory

SqlSessionFactory需要注入数据源跟mybatis路径,这样mybatis-config.xml配置的内容才能生效

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!-- 绑定mybatis配置文件 -->
    <property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
2.3.4 扫描映射器
  • MapperScannerConfigurer会自动扫描指定包下的所有mapper接口,为我们生成mapper接口的实现类并注入到Spring容器中。

  • 注入Spring容器中的的命名策略是使用映射器的非大写的非完全限定类名。可以通过注解@Repository("xx")来修改。

  • MapperScannerConfigurer是需要使用sqlSessionFactory的,但是当只有一个的时候可以省略,如果要显示注入可以使用如下代码注入来注入,注意这里引用上面的sqlSessionFactory,但是是value的属性值,而不是ref

    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>

  • 这是省略了sqlSession的,如果没有省略sqlSession则sqlSessionFactoryBeanName需要改成

sqlSessionTemplateBeanName`,并通过value值引入定义的sqlSession。
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.blb.ssm.dao"/>
		  
    <!-- 注入sqlSessionFactory,如果只有一个数据源可省略,自动装配,
  是value属性,不是ref -->
    <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> -->
	</bean>

2.4 spring-service.xml

2.4.1 自动扫描
<context:component-scan base-package="com.blb.ssm.service"/>
2.4.2 声明式事务

配置声明式事务,注入数据源,需要导入tx的命名空间。

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>
2.4.3 事务的注解驱动

需要注入2.4.2中定义的事务管理器。

<tx:annotation-driven transaction-manager="transactionManager"/>
2.4.4 BookServiceImpl.java
  • 需要增加@Service注解才能被spring扫描
  • 另外在方法中添加事务注解
  • @Transactional还可以直接修饰在类上,表示所有方法都加上事务
@Service
public class BookServiceImpl implements BookService{
	
	@Autowired
	private BookMapper bookMapper ;

	@Transactional 
	@Override
	public int addBook(Book book) {
		return bookMapper.addBook(book);
	}

	@Transactional 
	@Override
	public int updateBook(Book book) {
		return bookMapper.updateBook(book);
	}

	@Transactional 
	@Override
	public int deleteBook(int bookId) {
		return bookMapper.deleteBook(bookId);
	}

	// 不使用事务
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	@Override
	public List<Book> selectBooks() {
		return bookMapper.selectBooks();
	}

	// 不使用事务
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	@Override
	public Book selectBookById(int bookId) {
		return bookMapper.selectBookById(bookId);
	}

}

3、web+SpringMVC

3.1 web.xml

3.1.1 设置DispatcherServlet
<servlet>
		<servlet-name>springDispatcherServlet</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>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
3.1.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>

3.2 spring-control.xml

3.2.1 自动扫描
<context:component-scan base-package="com.blb.ssm.control"/>
3.2.2 注解驱动
<mvc:annotation-driven/>
3.2.3 静态资源过滤
<mvc:default-servlet-handler/>
3.2.4 视图解析器
<bean id="ResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

3.3 BookController.java

BookController类需要完成以下功能:

  • URL映射
  • 定义BookService并注入
  • 定义业务方法,通过BookService完成业务功能并跳转页面。
@Controller
@RequestMapping("/book")
public class BookController {
	
	@Autowired
	@Qualifier("bookServiceImpl")
	private BookService  bookService ;
	

	@RequestMapping("/queryAllBook")
	public String  queryAllBook(Model model){
		List<Book> list = bookService.selectBooks();
		model.addAttribute("bookList", list);
		return "hello";
	}

}

3.4 hello.jsp

在页面中取出数据并完成数据的显示。

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table border="1" align="center"  width="600px">
		<tr align="center">
			<td width="200px">书籍名称</td>
			<td width="200px">书籍价格</td>
			<td width="200px">书籍作者</td>
		</tr>

		<c:forEach items="${bookList}" var="book">
			<tr align="center">
				<td>${book.bookName }</td>
				<td>${book.bookPrice }</td>
				<td>${book.bookAuthor }</td>
			</tr>
		</c:forEach>
	</table>

</body>
</html>
上一篇:ssm框架写一个书本简单的增删改查 后台代码(跟着狂神视频整合的)


下一篇:mybatis 读取配置文件,得到SqlSessionFactory实例.