Spring SpringMvc Mybatis 整合
一. 配置类
1.1、 Spring配置类
@Configuration
@ComponentScan({"com.itheima.service"})
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {}
- @EnableTransactionManagement开启事务
1.2、SpringMvcConfig配置类
@Configuration
@ComponentScan("com.itheima.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
1.3. ServletConfig配置类
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[]{"/"};}// 乱码处理@Overrideprotected Filter[] getServletFilters() {CharacterEncodingFilter filter = new CharacterEncodingFilter();filter.setEncoding("UTF-8");return new Filter[]{filter};}
}
1.4. 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;@Beanpublic DataSource dataSource(){DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName(driver);dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);return dataSource;}@Beanpublic PlatformTransactionManager transactionManager(DataSource dataSource){DataSourceTransactionManager ds = new DataSourceTransactionManager();ds.setDataSource(dataSource);return ds;}
}
- 配置类内方法需要 使用@Bean注解, 注入到Spring中
1.5、Mybatis配置类
public class MybatisConfig {@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();factoryBean.setDataSource(dataSource);factoryBean.setTypeAliasesPackage("com.itheima.domain");return factoryBean;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer msc = new MapperScannerConfigurer();msc.setBasePackage("com.itheima.dao");return msc;}}
- 这里需要设置domain 和dao 层
1.6、jdbc配置文件 jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_db
jdbc.username=root
jdbc.password=mima1234
二、业务层
2.1、domain层
public class Book {private Integer id;private String type;private String name;private String description;@Overridepublic String toString() {return "Book{" +"id=" + id +", type='" + type + '\'' +", name='" + name + '\'' +", description='" + description + '\'' +'}';}public Integer getId() {return id;}public void setId(Integer 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;}
}
2.2、Dao层
public interface BookDao {//@Insert("insert into tbl_book values(null, #{type}, #{name}, #{description})")// 占位符表示的是book中的属性名@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();
}
2.3、Service接口和实现类
@Transactional
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();}@Service
public class BookServiceImpl implements BookService {@Autowiredprivate 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 false;}public Book getById(Integer id) {return bookDao.getById(id);}public List<Book> getAll() {return bookDao.getAll();}
}
2.4、控制器类
@RestController
@RequestMapping("/books")
public class BookController {@Autowiredprivate BookService bookService;@PostMappingpublic boolean save(@RequestBody Book book) {return bookService.save(book);}@PutMappingpublic 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);}@GetMappingpublic List<Book> getAll() {return bookService.getAll();}
}
三、封装返回值
3.1、Code类
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.2、Result类
public class Result {private Object data;private Integer code;private String msg;public Result() {}public Result( Integer code,Object data, String msg) {this.data = data;this.code = code;this.msg = msg;}public Result(Integer code,Object data) {this.data = data;this.code = code;}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;}
}
3.3、把控制器返回类型改成Result
@RestController
@RequestMapping("/books")
public class BookController {@Autowiredprivate BookService bookService;@PostMappingpublic Result save(@RequestBody Book book) {boolean flag = bookService.save(book);return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);}@PutMappingpublic 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 code = book != null ? Code.GET_OK : Code.GET_ERR;String msg = book != null ? "" : "数据查询失败,请重试!";return new Result(code, book, msg);}@GetMappingpublic Result getAll() {List<Book> books = bookService.getAll();Integer code = books != null ? Code.GET_OK : Code.GET_ERR;String msg = books != null ? "" : "数据查询失败,请重试!";return new Result(code, books, msg);}
}
四、异常
4.1、异常类
public class BusinessException extends RuntimeException {private Integer code;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public BusinessException(Integer code, String message) {super(message);this.code = code;}public BusinessException(Integer code, String message, Throwable cause) {super(message, cause);this.code = code;}}public class SystemException extends RuntimeException {private Integer code;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public SystemException(Integer code, String message) {super(message);this.code = code;}public SystemException( Integer code, String message, Throwable cause) {super(message, cause);this.code = code;}}
4.2、异常AOP
@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_UNKNOWN_ERR, null, "系统繁忙请稍后重试!!!");}
}
- @RestControllerAdvice 注解声明为AOP类 后,会自动注入到Spring内
4.3、异常使用
public Book getById(Integer id) {if( id == 1){throw new BusinessException(Code.BUSINESS_ERR, "请输入正确的年龄");}try {int i = 1 / 0;}catch (Exception e){throw new SystemException(Code.SYSTEM_ERR, "服务器异常", e);}return bookDao.getById(id);
}
-
根据情况抛出不同异常