一、创建工程
(1)使用IDEA创建一个Maven项目,具体可以参考这篇文章。
(2)项目用到的依赖添加到Pom.xml中
<!-- 打包方式--> <packaging>war</packaging> <!-- tomcat7插件--> <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>8080</port> <!-- GET请求乱码问题--> <uriEncoding>UTF-8</uriEncoding> </configuration> </plugin> </plugins> </build> <!-- SpringMVC--> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.10.RELEASE</version> </dependency> <!-- mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.24</version> </dependency> <!-- druid连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.10</version> </dependency> <!-- mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency> <!-- mybatis提供给Spring的接口--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.1.0</version> </dependency> <!-- SpringJDBC--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.4</version> </dependency> <!-- servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- Spring测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.10.RELEASE</version> </dependency> <!-- 导入JSON转换器-Jackson--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> </dependencies>
二、整合SSM配置
2.1 Spring
编写Spring配置类,用于代替ApplicationContext.xml文件,并扫描业务层的bean。
/** * Spring配置类 */ @Configuration // 设置当前类为Spring配置类 @ComponentScan({"com.itxiaoguo.service"}) // 扫描这些包下的bean @PropertySource(value = {"classpath:jdbc.properties"}) // 扫描这个资源 @Import({JdbcConfig.class, MybatisConfig.class}) // 导入这两个配置 @EnableTransactionManagement // 开启Spring事务支持 public class SpringConfig { }
2.2 Mybatis
(1)编写jdbc.properties文件,并放在resources目录下。
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=false jdbc.username=root jdbc.password=@123456
(2)编写JdbcConfig,用于创建数据源对象和管理JDBC事务。
/** * JDBC连接类 */ public class JdbcConfig { /** * 注入配置文件的信息——基本类型注入 */ @Value("${jdbc.driver}") private String driverClassName; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; /** * 创建数据源对象,传入给Mybatis * @return */ @Bean public DataSource getDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } /** * 编写JDBC事务管理器的Bean * @param dataSource * @return */ @Bean public PlatformTransactionManager transactionManager(DataSource dataSource) { DataSourceTransactionManager manager = new DataSourceTransactionManager(); manager.setDataSource(dataSource); return manager; } }
(3)编写MybatisConfig类,用于获取数据源对象和创建mapper代理。
public class MybatisConfig { @Bean public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource) { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); // 设置数据源 bean.setTypeAliasesPackage("com.itxiaoguo.bean"); // 设置类型别名的实体类 return bean; } @Bean public MapperScannerConfigurer getMapperScannerConfigurer() { MapperScannerConfigurer configurer = new MapperScannerConfigurer(); configurer.setBasePackage("com.itxiaoguo.mapper"); // 设置要生成代理的包 return configurer; } }
2.3 SpringMVC
(1)编写SpringMVC配置类,扫描controller层,并开启辅助支持。
/** * SpringMVC配置类 */ @Configuration @ComponentScan("com.itxiaoguo.controller") @EnableWebMvc public class SpringMvcConfig { }
(2)编写Servlet容器初始化类,并处理Post请求乱码问题。
/** * Servlet容器初始化类 */ public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer { /** * 导入Spring配置信息 * * @return */ @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{SpringConfig.class}; } /** * 告知Tomcat服务器这是SpringMVC项目 * * @return */ @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{SpringMvcConfig.class}; } /** * 将所有资源交给SpringMVC处理 * * @return */ @Override protected String[] getServletMappings() { return new String[]{"/"}; } /** * 解决POST请求中文乱码问题 * @return */ @Override protected Filter[] getServletFilters() { CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding("UTF-8"); return new Filter[]{filter}; } }
三、功能模块开发
public class Book { /** * 书籍id */ private Integer id; /** * 书籍类别 */ private String bookType; /** * 书名 */ private String bookName; /** * 书籍描述 */ private String bookDesc; // 省略了getter setter 有参 无参构造方法和toString()方法 }
3.2 mapper接口和自动代理
public interface BookMapper { /** * 添加书籍 * * @param book * @return */ @Insert("INSERT INTO book(book_type,book_name,book_desc) VALUES (#{bookType},#{bookName},#{bookDesc})") int addBook(Book book); /** * 修改书籍 * * @param book * @return */ @Update("UPDATE book SET book_type = #{bookType},book_name = #{bookName},book_desc = #{bookDesc} WHERE id = #{id}") int updateBookById(Book book); /** * 通过id删除书籍 * * @param id * @return */ @Delete("DELETE from book WHERE id = #{id}") int deleteBookById(@Param("id") Integer id); /** * 通过id查找书籍 * 使用@Results注解来映射数据库字段别名 * * @param id * @return */ @Select("SELECT * FROM book WHERE id = #{id}") @Results(id = "resultMaps", value = {@Result(column = "book_type", property = "bookType"), @Result(column = "book_name", property = "bookName"), @Result(column = "book_desc", property = "bookDesc")}) Book getBookById(@Param("id") Integer id); /** * 查询所有书籍 * * @return */ @Select("SELECT * FROM book") @ResultMap("resultMaps") List<Book> selectAll(); }
3.3 service接口和实现类
@Transactional public interface BookService { int addBook(Book book); int updateBookById(Book book); int deleteBookById(@Param("id") Integer id); Book getBookById(@Param("id") Integer id); List<Book> selectAll(); }
@Service public class BookServiceImpl implements BookService { @Autowired private BookMapper mapper; @Override public int addBook(Book book) { int i = mapper.addBook(book); return i; } @Override public int updateBookById(Book book) { int i = mapper.updateBookById(book); return i; } @Override public int deleteBookById(Integer id) { int i = mapper.deleteBookById(id); return i; } @Override public Book getBookById(Integer id) { Book book = mapper.getBookById(id); return book; } @Override public List<Book> selectAll() { List<Book> books = mapper.selectAll(); return books; } }
业务层接口测试:使用Junit测试