SSM整合
1.1ssm
-
首先导入jar包
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.10.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.10</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.16</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency>
-
创建jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm_db jdbc.username=root jdbc.password=root
-
创建配置文件SpringConfig,SpringMvcConfig
//springConfig @Configuration @ComponentScan({"com.scidag.service","com.scidag.controller"}) @PropertySource("classpath:jdbc.properties") @Import({JdbcConfig.class,MybatisConfig.class}) @EnableTransactionManagement public class SpringConfig { } //SpringMvcConfig @Configuration @ComponentScan("com.scidag.controller") @EnableWebMvc public class SpringMvcConfig { }
-
创建JdbcConfig,MybatisConfig
//JdbcConfig public class JdbcConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean public DataSource dataSource(){ DruidDataSource dataSource=new DruidDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } @Bean public PlatformTransactionManager transactionManager(DataSource dataSource){//设置spring事务 DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager(); dataSourceTransactionManager.setDataSource(dataSource); return dataSourceTransactionManager; } }
//MybatisConfig public class MybatisConfig { @Bean public SqlSessionFactoryBean sqlSessionFactoryBean( DataSource dataSource){ SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean(); sqlSessionFactoryBean.setTypeAliasesPackage("com.scidag.pojo"); sqlSessionFactoryBean.setDataSource(dataSource); return sqlSessionFactoryBean; } @Bean public MapperScannerConfigurer mapperScannerConfigurer(){ MapperScannerConfigurer mapperScannerConfigurer=new MapperScannerConfigurer(); mapperScannerConfigurer.setBasePackage("com.scidag.dao"); return mapperScannerConfigurer; } }
-
创建ServletConfig
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{SpringConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{SpringMvcConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
-
创建Dao和Service
public interface BookDao { @Insert("insert into tbl_book (name,type,description) values(#{name}, #{type}, #{description})") void save(Book book); @Delete("delete from tbl_book where id=#{id}") void delete(Integer id); @Update("update tbl_book set type=#{type}, name=#{name}, description=#{description} where id=#{id}") void update(Book book); @Select("select * from tbl_book where id =#{id}") Book selectByID(Integer id); @Select("select * from tbl_book") List<Book> selectAll(); }
public interface BookService { /** * 保存 * @param book * @return */ boolean save(Book book); /** * 删除 * @param id * @return */ boolean delete(Integer id); /** * 修改 * @param book * @return */ boolean update(Book book); /** * 查单个 * @param id * @return */ Book selectByID(Integer id); /** * 查所有 * @return */ List<Book> selectAll(); }
@Service public class BookServiceImpl implements BookService { @Autowired private BookDao bookDao; @Override public boolean save(Book book) { bookDao.save(book); return true; } @Override public boolean delete(Integer id) { bookDao.delete(id); return true; } @Override public boolean update(Book book) { bookDao.update(book); return true; } @Override public Book selectByID(Integer id) { return bookDao.selectByID(id); } @Override public List<Book> selectAll() { return bookDao.selectAll(); } }
-
创建pojo
对应数据库中的属性名和类型,提供对应的get set toString 方法即可
-
创建controller
@RestController @RequestMapping("/books") public class BookController { @Autowired private BookService bookService; @PostMapping public boolean save(@RequestBody Book book){ return bookService.save(book); } @PutMapping public boolean update(@RequestBody Book book){ return bookService.update(book); } @DeleteMapping("/{id}") public boolean delete(Integer id){ return bookService.delete(id); } @GetMapping("/{id}") public Book selectByID(Integer id) { return bookService.selectByID(id); } @GetMapping public List<Book> selectAll(){ return bookService.selectAll(); } }
1.2统一结果封装
对于3.1来说,返回结果的boolean类型数据,而select则返回的一个对象
为了返回一个统一的数据结果,前端解析更简单.
-
设置一个统一返回结果类
Result class... {
private Object data; private Integer code; private String msg;
}
-
定义返回码状态类
//状态码 public class Code { public static final Integer SAVE_OK = 20011; public static final Integer DELETE_OK = 20021; public static final Integer UPDATE_OK = 20031; public static final Integer GET_OK = 20041; public static final Integer SAVE_ERR = 20010; public static final Integer DELETE_ERR = 20020; public static final Integer UPDATE_ERR = 20030; public static final Integer GET_ERR = 20040; }
-
colltroller中使用
@PostMapping public Result save(@RequestBody Book book){ boolean save = bookService.save(book); return new Result(save? Code.insert_success:Code.insert_err,save) ; }
1.3统一异常处理
异常种类和异常原因
框架内部抛出的异常:因使用不合规导致 数据层抛出的异常:因外部服务器故障导致(例如:服务器访问超时) 业务层抛出的异常:因业务逻辑书写错误导致(例如:遍历业务书写操作,导致索引异常等) 表现层抛出的异常:因数据收集、校验等规则导致(例如:不匹配的数据类型间导致异常) 工具类抛出的异常:因工具类书写不严谨不够健壮导致(例如:必要释放的连接长期未释放等)
处理方式:新建一个异常包,新建异常类
package com.scidag.Exception; public class BusinessException extends RuntimeException{ private Integer code; public BusinessException() { } public BusinessException(Integer code) { this.code = code; } public BusinessException(String message, Integer code) { super(message); this.code = code; } public BusinessException(String message, Throwable cause, Integer code) { super(message, cause); this.code = code; } public BusinessException(Throwable cause, Integer code) { super(cause); this.code = code; } public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Integer code) { super(message, cause, enableSuppression, writableStackTrace); this.code = code; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } } -------------------------------------------------- package com.scidag.Exception; public class SystemExcrption extends RuntimeException{ private Integer code; public SystemExcrption(Integer code) { this.code = code; } public SystemExcrption() { } public SystemExcrption(String message, Integer code) { super(message); this.code = code; } public SystemExcrption(String message, Throwable cause, Integer code) { super(message, cause); this.code = code; } public SystemExcrption(Throwable cause, Integer code) { super(cause); this.code = code; } public SystemExcrption(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Integer code) { super(message, cause, enableSuppression, writableStackTrace); this.code = code; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } } --------------------------- controller package com.scidag.controller; import com.scidag.Exception.BusinessException; import com.scidag.Exception.SystemExcrption; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class ProjectExcptionAdvice { @ExceptionHandler(SystemExcrption.class) public Result doSystemExcrption(SystemExcrption e){ return new Result(e.getCode(),null ,e.getMessage()); } @ExceptionHandler(BusinessException.class) public Result doBusinessExcrption(BusinessException e){ return new Result(e.getCode(),null ,e.getMessage()); } @ExceptionHandler(Exception.class) public Result doExcrption(Exception e){ System.out.println("有异常"); return new Result(Code.SYSTEM_UNKNOW_ERR,null ,"处理异常"); } }