SpringBoot整合SSM

该文章展示了如何在SpringBoot项目中整合Spring、SpringMVC和MyBatis(SSM),包括Book实体类的定义,DAO接口及实现,Controller层的RESTfulAPI设计,以及自定义异常和全局异常处理。此外,还涉及到事务管理和服务层的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot整合SSM

damain层

package com.example.demo.domain;

public class Book {
    private int id;
    private String type;
    private String name;
    private String description;

    public Book(int id, String type, String name, String description) {
        this.id = id;
        this.type = type;
        this.name = name;
        this.description = description;
    }

    public Book() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", type='" + type + '\'' +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}

dao层:

package com.example.demo.dao;
import com.example.demo.domain.Book;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
@Mapper

public interface BookDao {
    @Insert("insert into tb_book (type,name,description) values(#{type},#{name},#{description})")
    public int save(Book book);
    @Update("update tb_book set type=#{type},name=#{name},description=#{description} where id=#{id}")
    public int update(Book book);
    @Delete("delete from tb_book where id=#{id}")
    public int delete(int id);
    @Select("select * from tb_book")
    public List<Book> findAll();
    @Select("select * from tb_book where id=#{id}")
    public Book getById(int id);
}

controller层:

//拦截器

package com.example.demo.controller.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ProjectInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String contenType=request.getHeader("123");
        System.out.println(handler);
        System.out.println("preHandle---"+handler);
        System.out.println("dgdjd-前---");
        return  true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        System.out.println("dgdjd-运行中---");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        System.out.println("dgdjd-后---");
    }
}
package com.example.demo.controller;
import com.example.demo.domain.Book;
import com.example.demo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/books")
public  class BookController {
    @Autowired
    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 int id) {
       boolean flag=  bookService.delete(id);
       return  new Result(flag?Code.DELETE_OK:Code.DELETE_ERR,flag);

    }

    @GetMapping
    public Result findAll() {


        List<Book> bookList= bookService.findAll();
        Integer code=bookList!=null?Code.GET_OK:Code.GET_ERR;
        String msg=bookList!=null?"":"数据查询失败,请重试";
        return new Result(code,bookList,msg);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable int id) {
        Book book=bookService.getById(id);
        Integer code=book!=null?Code.GET_OK:Code.GET_ERR;
        String msg=book!=null?"":"数据查询失败,请重试";
        return new Result(code,book,msg);
    }
}
package com.example.demo.controller;
//错误类型协议
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;

    public static final Integer SYSTEM_ERR=50001;
    public static final Integer SYSTEM_TIMEOUT_ERR=50002;
    public static final Integer BUSINESS_ERR=60002;
    public static final Integer SYSTEM_UNKNOW_ERR=60009;




}

//异常处理器
package com.example.demo.controller;
import com.example.demo.exception.BusinessException;
import com.example.demo.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ProjectExceptionAdvice {
    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException ex){
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员
        return new Result(ex.getCode(),null,ex.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public Result doBusinessException(BusinessException ex){
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员
        return new Result(ex.getCode(),null,ex.getMessage());
    }
    @ExceptionHandler(Exception.class)
    public Result doException(Exception ex){
        return new Result(Code.SYSTEM_UNKNOW_ERR,null,"请勿非法操作");
    }

}

//自定义异常
package com.example.demo.exception;

public class BusinessException extends RuntimeException {
    private Integer code;

    public Integer getCode() {
        return code;
    }

    public void setCode(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;
    }

}

//自定义异常
package com.example.demo.exception;
public class SystemException extends RuntimeException{
    private Integer code;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public SystemException(String message, Integer code) {
        super(message);
        this.code = code;
    }

    public SystemException(String message, Throwable cause, Integer code) {
        super(message, cause);
        this.code = code;
    }

}
package com.example.demo.service.Impl;

import com.example.demo.controller.Code;
import com.example.demo.dao.BookDao;
import com.example.demo.domain.Book;
import com.example.demo.exception.SystemException;
import com.example.demo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    @Override
    public boolean save(Book book) {
        return bookDao.save(book) > 0;


    }

    @Override
    public boolean update(Book book) {
        return bookDao.update(book) > 0;


    }

    @Override
    public boolean delete(int id) {
        return bookDao.delete(id) > 0;


    }

    @Override
    public List<Book> findAll() {
        return bookDao.findAll();
    }

    @Override
    public Book getById(int id) {
        if (id == 1) {
            throw new SystemException("服务器连接超时", Code.BUSINESS_ERR);
        }

/*
        //将可能出现的异常进行包装,转换为自定义异常
        try{
            int i=1/0;
        }catch (Exception e){
            throw new SystemException("服务器访问超时,请重试",e,Code.SYSTEM_TIMEOUT_ERR);
        }

         */

        return bookDao.getById(id);
    }
}

service层:

package com.example.demo.service;

import com.example.demo.domain.Book;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
public interface BookService {


    /**
     * 保存
     * @return
     */
    public boolean save(Book book);

    /**
     * 修改
     * @return
     */
    public boolean update(Book book);

    /**
     * 删除
     * @param id
     * @return
     */
    public boolean delete(int id);

    /**
     * 查询
     * @return
     */
    public List<Book> findAll();

    /**
     * 按id查询
     * @param id
     * @return
     */
    public Book getById(int id);

}

application:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
//yml格式配置资源

server:
  port: 8080
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/user
    username: root
    password: 123456
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值