一、配置pom.xml,添加依赖
<?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>com.qianfeng</groupId>
<artifactId>SsmDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!--统一管理spring所有的版本-->
<properties>
<spring-version>4.3.6.RELEASE</spring-version>
</properties>
<dependencies>
<!--springmvc的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<!--rest风格使用-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.10</version>
</dependency>
<!--mariadb-->
<dependency>
<groupId>mariadb</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>1.8.0</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--mybatis spring的插件,将mybatis交给spring来管理-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--spring的单元测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<!--spring jdbc,包含事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- spring aop的面向切面的配置-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>com.springsource.org.aspectj.weaver</artifactId>
<version>1.6.8.RELEASE</version>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.28</version>
</dependency>
<!--日志信息-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- 添加tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8080</port>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
</plugins>
</build>
</project>
二、在WEB-INF下新建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_3_1.xsd"
version="3.1">
<!--配置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>
</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>
三、在resource目录下配置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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<!--<property name="suffix" value=".jsp"></property>-->
</bean>
<!--配置缺省的servlet处理器,静态资源可以直接被访问-->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<!--上下文的组件扫描-->
<!--设置包扫描,分别扫描controller和service包-->
<!--<context:component-scan base-package="com.qianfeng" />-->
<!--扫描所有包也行-->
<context:component-scan base-package="com.qianfeng.controller"></context:component-scan>
<context:component-scan base-package="com.qianfeng.service" />
<!--配置注解驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--设置ssm的整合注解配置-->
<context:annotation-config />
<!--引入spring和mybatis的整合文件-->
<import resource="classpath:spring-mybatis.xml" />
</beans>
四、在resource目录下配置spring-mybatis.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-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 配置druid数据源 -->
<!--driver的name应为driverClassName-->
<bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="org.mariadb.jdbc.Driver"/>
<property name="url" value="jdbc:mariadb://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="yutong19970820"/>
</bean>
<!--我们知道在Mybatis的所有操作都是基于一个SqlSession的,而SqlSession是由SqlSessionFactory来产生
的,SqlSessionFactory又是由SqlSessionFactoryBuilder来生成的。但是Mybatis-Spring是基于
SqlSessionFactoryBean的。在使用Mybatis-Spring的时候,我们也需要SqlSession,而且这个SqlSession是
内嵌在程序中的,一般不需要我们直接访问。SqlSession也是由SqlSessionFactory来产生的,但是Mybatis
Spring给我们封装了一个SqlSessionFactoryBean,在这个bean里面还是通过SqlSessionFactoryBuilder来建
立对应的SqlSessionFactory,进而获取到对应的SqlSession。通过SqlSessionFactoryBean我们可以通过对
其指定一些属性来提供Mybatis的一些配置信息。-->
<bean id="sf" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.qianfeng.bean" />
<property name="mapperLocations" value="classpath:Mapper/*Mapper.xml" />
<property name="dataSource" ref="ds"></property>
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<!--Mybatis-Spring为我们提供了一个叫做MapperScannerConfigurer的类,通过这个类
Mybatis-Spring会自动为我们注册Mapper对应的MapperFactoryBean对象。 如果我们
需要使用MapperScannerConfigurer来帮我们自动扫描和注册Mapper接口的 话我们需要
在Spring的applicationContext配置文件中定义一个MapperScannerConfigurer对应
的bean。对于MapperScannerConfigurer而言有一个 属性是我们必须指定的,那就是
basePackage。basePackage是用来指定Mapper接口 文件所在的基包的,在这个基包或
其所有子包下面的Mapper接口都将被搜索到。多个基 包之间可以使用逗号或者分号进行分隔。
最简单的MapperScannerConfigurer定义就是 只指定一个basePackage属性。-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.qianfeng.dao" />
<property name="sqlSessionFactoryBeanName" value="sf" />
</bean>
<!-- 配置事务管理器 -->
<bean id="dtx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="ds"></property>
</bean>
<tx:advice id="tx" transaction-manager="dtx">
<!-- 声明属性,声明事务的规则 -->
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<!-- 定义切面 -->
<aop:config>
<aop:pointcut id="mpt" expression="execution(* com.qianfeng.service.*.*(..))" />
<aop:advisor advice-ref="tx" pointcut-ref="mpt" />
</aop:config>
</beans>
其中
1、配置druid数据源时,driver的name应为driverClassName
2、如果想用MySQL数据库,则driverClassName的value改为"com.mysql.jdbc.Driver",url改为"jdbc:mysql://localhost:3307/我的数据库名"
3、<property name="mapperLocations" value="classpath:Mapper/Mapper.xml" />应填Mapper.xml所在位置。因为我的IDEA版本若将Mapper放在dao下无法扫描到,因此必须放到resource下
4、<property name="basePackage" value="com.qianfeng.dao" 给出的是需要扫描的Dao接口包/>
五、在resour目录下配置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>
<settings>
<setting name="logImpl" value="LOG4J" />
</settings>
</configuration>
resource下的log4j.properties:
# Global logging configuration
log4j.rootLogger=ERROR, stdout, F
# MyBatis logging configuration...
log4j.logger.com.qfedu.dao=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
log4j.appender.F = org.apache.log4j.DailyRollingFileAppender
log4j.appender.F.File =myproj.log
log4j.appender.F.Append = true
log4j.appender.F.Threshold = DEBUG
log4j.appender.F.layout=org.apache.log4j.PatternLayout
log4j.appender.F.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss}-[%p %F\:%L] %m%n
六、配置文件结束,环境搭建完毕,开始编写代码,先是图书类BookBean类
public class BookBean {
private int id;
private String name;
private double price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("BookBean{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append(", price=").append(price);
sb.append('}');
return sb.toString();
}
}
七、dao层,BookDao的接口类
public interface BookDao {
List<BookBean> getAllBooks();
}
八、service层
1、 注意Service的实现类之上一定要添加service注解
2、用@Resource(或@Autowired)动态注入dao组件
/**
* 注意Service的实现类之上一定要添加service注解
*/
@Service
public class BookService {
/**
* 动态注入dao组件
*/
@Resource
private BookDao bookDao;
public List<BookBean> getAllBooks(){
return bookDao.getAllBooks();
}
}
九、controller层
1、Controller 实现类上要添加注解@RestController(用@RestController无法返回jsp页面,如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。)
2、用@Resource(或@Autowired)动态注入service组件
@RestController
public class Controller {
@Resource
private BookService bookService;
@RequestMapping("/book")
public List<BookBean> getAllBooks(){
return bookService.getAllBooks();
}
}
十、在resource目录下新建一个Mapper文件夹,在里面创建BookMapper.xml
namespace必须是dao接口的全路径
<?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">
<!--
第二种实现mybatis的方式为:接口+xml方式
这种方式有特别的要求
1. namespace必须是接口的全路径
2. 每个节点的id必须是接口中的方法名
3. 该接口中的方法不允许重载,否则namespace+id将不唯一
4. 注意该接口中的增删改的方法的返回值,最好使用int
-->
<mapper namespace="com.qianfeng.dao.BookDao">
<!--查询全部图书(进行展示)-->
<select id="getAllBooks" resultType="com.qianfeng.bean.BookBean">
select * from springmvcbook
</select>
</mapper>