SSM框架是Spring、Spring MVC和MyBatis三个开源框架的整合,常用于构建数据源较简单的web项目。该框架是Java EE企业级开发的主流技术,也是每一个java开发者必备的技能。下面通过查询书籍列表的案例演示SSM整合的过程.
完整文件结构
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!--spring和springMVC环境依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.18.RELEASE</version>
</dependency>
<!--servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--spring事务管理依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.18.RELEASE</version>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--spring整合mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--spring整合数据源依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
<!--mysql数据库连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!--spring整合Junit依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.18.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
<!--日志支持-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
在resources目录下的props包中创建jdbc.properties文件
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=mysqlpass
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
@Configuration
//加载资源路径
@PropertySource("classpath:props/jdbc.properties")
public class JdbcConfig {
@Value("${jdbc.driverClass}")
private String driverClass;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.url}")
private String url;
/**配置Druid数据源*/
/**@Bean将返回的dataSource标识为被Spring管理的bean对象*/
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setUrl(url);
return dataSource;
}
}
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import javax.sql.DataSource;
import java.io.IOException;
@Configuration
@Import(JdbcConfig.class)
public class MyBatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
//加载全局配置文件
Resource configResource = new ClassPathResource("mybatis/mybatis-config.xml");
sessionFactoryBean.setConfigLocation(configResource);
//映射文件加载
ResourcePatternResolver resourceResolver= new PathMatchingResourcePatternResolver();
sessionFactoryBean.setMapperLocations(resourceResolver.getResources("classpath*:mybatis/mapper/*Mapper.xml"));
return sessionFactoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
//扫描mapper接口所在的包
scannerConfigurer.setBasePackage("com.yaorange.ssm.mapper");
return scannerConfigurer;
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration
//扫描业务类实现类所在的包
@ComponentScan("com.yaorange.ssm.service.impl")
//加载MyBatisConfig和JdbcConfig配置类的字节码文件
@Import({MyBatisConfig.class, JdbcConfig.class})
//开启事务管理器
@EnableTransactionManagement
public class SpringConfig {
@Bean
/**配置事务管理器*/
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
@Configuration
//扫描controller所在的包
@ComponentScan("com.yaorange.ssm.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
/**加载Spring配置,创建Spring容器*/
protected Class<?>[] getRootConfigClasses() {
return new Class[] {SpringConfig.class};
}
@Override
/**加载SpringMVC配置,创建SpringMVC容器*/
protected Class<?>[] getServletConfigClasses() {
return new Class[] {SpringMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
//所有请求都交给SpringMVC处理
return new String[] {"/"};
}
}
@Data
public class Books implements Serializable {
/**
* 书籍编号
*/
private Integer bId;
/**
* 书籍名称
*/
private String bName;
/**
* 作者
*/
private String authers;
/**
* 价格
*/
private BigDecimal price;
/**
* 出版年份
*/
private Object pubdate;
/**
* 备注
*/
private String note;
/**
* 数量
*/
private Integer num;
}
public interface BooksMapper {
/**查询所有书籍*/
List<Books> selectAll();
}
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.yaorange.ssm.mapper.BooksMapper">
<resultMap id="BaseResultMap" type="com.yaorange.ssm.entity.Books">
<id property="bId" column="b_id" jdbcType="INTEGER"/>
<result property="bName" column="b_name" jdbcType="VARCHAR"/>
<result property="authers" column="authers" jdbcType="VARCHAR"/>
<result property="price" column="Price" jdbcType="DECIMAL"/>
<result property="pubdate" column="pubdate" jdbcType="OTHER"/>
<result property="note" column="note" jdbcType="VARCHAR"/>
<result property="num" column="num" jdbcType="INTEGER"/>
</resultMap>
<sql id="Base_Column_List">
b_id,b_name,authers,
Price,pubdate,note,
num
</sql>
<select id="selectAll" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM
books
</select>
</mapper>
public interface BookService {
List<Books> selectAll();
}
@Service
//开启事务管理
@Transactional(rollbackFor = Exception.class)
public class BookServiceImpl implements BookService {
@Autowired
private BooksMapper booksMapper;
@Override
public List<Books> selectAll() {
return booksMapper.selectAll();
}
}
@Controller
@ResponseBody
//根路径
@RequestMapping("/book")
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping("/list")
public Result selectAll(){
List<Books> books = bookService.selectAll();
return Result.ok(books);
}
}
将多余的删除后点击apply
/**定义响应结果类*/
@Data
public class Result {
//响应码
private int code;
//响应信息
private String msg;
//响应数据
private Object data;
public Result(int code, String msg) {
this.code = code;
this.msg = msg;
}
public Result(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public Result(String msg, Object data) {
this.msg = msg;
this.data = data;
}
public Result(Object data) {
this.data = data;
}
public static Result success (){
return new Result(HttpCode.SUCCESS_CODE,HttpMsg.SYS_OK_MSG);
}
public static Result ok(Object data){
return new Result(data);
}
public static Result ok(String msg,Object data){
return new Result(msg, data);
}
}
public interface HttpCode {
//成功响应码
int SUCCESS_CODE=200;
//失败响应码
int ERROR_CODE=500;
}
public class HttpMsg {
public static final String SYS_ERROR_MSG="操作失败";
public static final String SYS_OK_MSG="操作成功";
}