持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第9天,点击查看活动详情
SSM整合流程
2.SSM整合
spring
先导入坐标(一大堆)
创建SpringConfig配置类
@Configuration
@ComponentScan({"com.itheima.service"})
public class SpringConfig {
}
mybatis与spring整合
1.
创建jdbcConfig,MybatisConfig配置类,jdbc.propeties并在里面输入相应信息
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;
}
public class MybatisConfig{
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setTypeAliasesPackage("com.itheima.domain");
return factoryBean;
}
//扫描映射
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.itheima.dao");
return msc;
}
jdbc.propeties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db
jdbc.username=root
jdbc.password=z15788901
再在SpringConfig配置类中加入如下注解
@Configuration
@ComponentScan({"com.itheima.service"})
@PropertySource("jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}
这样就完成了spring整合mybatis
spring整合springMVC
1.创建SpringMvcConfig,加上如下注解
@Configuration
@ComponentScan("com.itheima.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
2.创建ServletConfig并继承AbstractAnnotationConfigDispatcherServletInitializer重写方法
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
//拦截所有请求
protected String[] getServletMappings() {
return new String[]{"/"};
}
这样,就完成了spring整合springMVC的操作。
3.功能模块
1.先导入表与创建实体类
2.dao
public interface BookDao {
@Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
public void save(Book book);
@Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
public void update(Book book);
@Delete("delete from tbl_book where id = #{id}")
public void delete(Integer id);
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
@Select("select * from tbl_book")
public List<Book> getAll();
}
3.BookServiceImpl
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
public boolean save(Book book) {
bookDao.save(book);
return true;
}
public boolean update(Book book) {
bookDao.update(book);
return true;
}
public boolean delete(Integer id) {
bookDao.delete(id);
return true;
}
public Book getById(Integer id) {
return bookDao.getById(id);
}
public List<Book> getAll() {
return bookDao.getAll();
}
}
4.BookController
@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(@PathVariable Integer id) {
return bookService.delete(id);
}
@GetMapping("/{id}")
public Book getById(@PathVariable Integer id) {
return bookService.getById(id);
}
@GetMapping
public List<Book> getAll() {
return bookService.getAll();
}
5.BookService
public interface BookService {
/**
* 保存
* @param book
* @return
*/
public boolean save(Book book);
/**
* 修改
* @param book
* @return
*/
public boolean update(Book book);
/**
* 按id删除
* @param id
* @return
*/
public boolean delete(Integer id);
/**
* 按id查询
* @param id
* @return
*/
public Book getById(Integer id);
/**
* 查询全部
* @return
*/
public List<Book> getAll();
}
业务层接口测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void test(){
Book book = bookService.getById(2);
System.out.println(book);
}
@Test
public void testAll(){
List<Book> all = bookService.getAll();
System.out.println(all);
}
再用POSTman测试各网页即可。
事务处理
1.开启注解式事务驱动
在springconfig类中加入如下注解
@EnableTransactionManagement
2.配置事务管理器
在jdbcconfig类中加入如下方法
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager ds = new DataSourceTransactionManager();
ds.setDataSource(dataSource);
return ds;
}
3.添加事务,把事务的Transactional添加到接口上
在service接口中加入如下注解
@Transactional
下面是高级部分:
表现层数据封装
目的:统一成相同格式,称之为表现层与前端数据传输协议
方案:创建结果模型类,
封装数据到data属性中,
封装操作结果到code属性中,
封装特殊消息到message(msg)属性中
步骤:
1.造result类
public class Result {
private Object data;
private Integer code;
private String msg;
public Result(Object data, Integer code) {
this.data = data;
this.code = code;
}
public Result() {
}
public Result(Object data, Integer code, String msg) {
this.data = data;
this.code = code;
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
2.创建code类,用来表示返回的code为什么值时表示成功,失败
PS:Code类的常量设计也不是固定的,可以根据需要自行增减,例如将查询再进行细分为GET_OK,GET_ALL_OK,GET_PAGE_OK
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;
}
3.在BookController中修改如下
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public Result save(@RequestBody Book book) {
boolean flag = bookService.save(book);
return new Result(flag?code.SAVE_OK:code.SAVE_ERR,flag);
}
@PutMapping
public Result update(@RequestBody Book book) {
boolean flag = bookService.update(book);
return new Result(flag?code.UPDATE_OK:code.UPDATE_ERR,flag);
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
boolean flag = bookService.delete(id);
return new Result(flag?code.DELETE_OK:code.DELETE_ERR,flag);
}
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id) {
Book book = bookService.getById(id);
Integer code1 = book != null ? code.GET_OK:code.GET_ERR;
String msg = book != null ? "":"查询失败";
return new Result(code1,book,msg);
}
@GetMapping
public Result getAll() {
List<Book> bookList = bookService.getAll();
Integer code1 = bookList != null ? code.GET_OK:code.GET_ERR;
String msg = bookList != null ? "":"查询失败";
return new Result(code1,bookList,msg);
}
异常处理器
出现异常现象的常见位置与常见诱因如下:
框架内部抛出的异常:因使用不合规导致
数据层抛出的异常:因外部服务器故障导致(例如∶服务器访问超时)
业务层抛出的异常:因业务逻辑书写错误导致(例如:遍历业务书写操作,导致索引异常等)
表现层抛出的异常:因数据收集、校验等规则导致(例如:不匹配的数据类型间导致异常)
工具类抛出的异常:因工具类书写不严谨不够健壮导致(例如:必要释放的连接长期未释放等)
1.各个层级均出现异常,异常处理代码书写在哪一层?
所有的异常均抛出到表现层进行处理
2.表现层处理异常,每个方法中单独书写,代码书写量巨大且意义不强,如何解决?
AOP思想
代码实现如下
//用来做异常处理的类
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler(Exception.class)
public void doException(Exception ex){
System.out.println("异常我lei了");
}
上面讲述的是表现层如何抛出异常,那么,数据层,业务层的异常该如何整合到表现层呢?
项目异常处理方案
项目异常分类:
-
业务异常(BusinessException)
- 规范的用户行为产生的异常术
- 不规范的用户行为操作产生的异常
-
系统异常(SystemException)
- 项目运行过程中可预计且无法避免的异常
-
其他异常(Exception)
- 编程人员未预期到的异常
public class ProjectExceptionAdvice {
@ExceptionHandler(SystemException.class)
public Result doSystemException(SystemException ex){//系统异常
//记录日志
//发送消息给运维
//发送邮件给开发人员
return new Result(ex.getCode(),null,ex.getMessage());
}
@ExceptionHandler(BussinessException.class)//业务异常
public Result BussinessException(BussinessException bx){
return new Result(bx.getCode(),null,bx.getMessage());
}
@ExceptionHandler(Exception.class)
public Result doException(Exception ex){//其他异常
//记录日志
//发送消息给运维
//发送邮件给开发人员
System.out.println("异常我lei了");
return new Result(code.SYSTEM_UNKNOWN_ERR,null,"系统繁忙,请稍后再试");
}
public Book getById(Integer id) {
if(id==1){
throw new BussinessException(code.BUSINESS_ERR,"请你自重");
}
//将可能出现的异常进行包装,转换成自定义异常
try{
int i = 1/0;
}catch (Exception e){
throw new SystemException(code.SYSTEM_ERR,"服务器访问超时,请重试",e);
}
return bookDao.getById(id);
}