SSM(spring+springmvc+mybatis)完全注解开发整合
目录结构如图:
创建数据库
create database mydb;
use mydb;
create table tbl_users(
id int primary key auto_increment,
username varchar(20),
password varchar(20),
age int,
birthday date
);
insert tbl_users(username,password,age,birthday)values
("张三","123456",11,'2022-09-09'),
("李四","123456",12,'2022-09-10'),
("王五","123456",13,'2022-09-12'),
("赵六","123456",14,'2022-09-14')
持久类Users编写
package com.qwy.bean;
import java.util.Date;
public class Users {
private Integer id;
private String username;
private String password;
private int age;
private Date birthday;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
Spring的配置类SpringConfig
package com.qwy.config;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration//标注该类为一个配置类,这里配置Spring的信息
@ComponentScan(value = {"com.qwy"},excludeFilters = @ComponentScan.Filter(
type = FilterType.ANNOTATION,
classes = Controller.class
))//配置Spring管理的bean所要扫描的包,需要将@Controller注解排除在外
@PropertySource({"classpath:db.properties"})//加载数据库的配置属性文件
@Import({JdbcConfig.class,MyBatisConfig.class})//加载数据源和mybatis的配置
@EnableTransactionManagement//开启注解的事务管理
public class SpringConfig {
}
SpringMVC的配置类SpringMvcConfig
package com.qwy.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration//标注该类为一个配置类,此类为SpringMVC的配置信息
@ComponentScan({"com.qwy.controller","com.qwy.exception"})
@EnableWebMvc//该注解可以自动开启JSON的自动转换
public class SpringMvcConfig {
}
WEB容器初始化类ServletContainerConfig
package com.qwy.config;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
/**
* 配置注解式的WEB容器(web.xml)
*/
public class ServletContainerConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
/**
* 加载Spring的配置
* @return
*/
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
/**
* 加载SpringMVC的配置
* */
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
/*
* 配置SpringMVC核心处理的拦截路径
* */
protected String[] getServletMappings() {
return new String[]{"/"};
}
/**
* 配置Post请求乱码处理的过滤器
* */
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter= new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
return new Filter[]{characterEncodingFilter};
}
}
数据库属性配置文件db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb?serverTimezone=UTC
jdbc.username=root
jdbc.password=admin
数据源配置类JdbcConfig
package com.qwy.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
/**
* 配置数据源
* 这里使用阿里的数据源
*/
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;
}
/**
* 平台事务管理器
* @param dataSource
* @return
*/
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager transactionManager= new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
Mybatis配置类MybatisConfig
package com.qwy.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MyBatisConfig {
@Bean
public SqlSessionFactoryBean sessionFactoryBean(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean= new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage("com.qwy.bean");
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScannerConfigurer= new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.qwy.dao");
return mapperScannerConfigurer;
}
}
持久化类UsersMapper
package com.qwy.dao;
import com.qwy.bean.Users;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface UsersMapper {
/**
* 添加
* @param users
* @return
*/
@Insert("insert into tbl_users(username,password,age,birthday)values(#{username},#{password},#{age},#{birthday})")
int save(Users users);
/**
* 根据id删除
* @param id
* @return
*/
@Delete("delete from tbl_users where id=#{id}")
int delete(Integer id);
/**
* 根据id修改
* @param users
* @return
*/
@Update("update tbl_users set username=#{username},password=#{password},age=#{age},birthday=#{birthday} where id =#{id}")
int update(Users users);
/**
* 根据id查询
* @param id
* @return 返回单个用户
*/
@Select("select * from tbl_users where id=#{id}")
Users findById(Integer id);
/**
* 查询全部结果
* @return
*/
@Select("select * from tbl_users")
List<Users> findAll();
}
业务接口
package com.qwy.service;
import com.qwy.bean.Users;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional//开启事务
public interface UsersService {
/**
* 添加
* @param users
* @return
*/
boolean save(Users users);
/**
* 根据id删除
* @param id
* @return
*/
boolean delete(Integer id);
/**
* 根据id修改
* @param users
* @return
*/
boolean update(Users users);
/**
* 获取单个用户
* @param id
* @return
*/
Users findById(Integer id);
/**
* 获取全部
* @return
*/
List<Users> findAll();
}
业务接口实现类
package com.qwy.service.impl;
import com.qwy.bean.Users;
import com.qwy.dao.UsersMapper;
import com.qwy.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UsersServiceImpl implements UsersService {
@Autowired
private UsersMapper usersMapper;
public boolean save(Users users) {
int i=9/0;
return usersMapper.save(users)>0?true:false;
}
public boolean delete(Integer id) {
return usersMapper.delete(id)>0?true:false;
}
public boolean update(Users users) {
return usersMapper.update(users)>0?true:false;
}
public Users findById(Integer id) {
return usersMapper.findById(id);
}
public List<Users> findAll() {
return usersMapper.findAll();
}
}
自定义状态码类Code
package com.qwy.controller;
/**
* 该类用来定义状态码
*/
public class Code {
public static final Integer SAVE_OK=20021;
public static final Integer DELETE_OK=20022;
public static final Integer UPDATE_OK=20023;
public static final Integer SELECT_OK=20024;
public static final Integer SAVE_ERR=20011;
public static final Integer DELETE_ERR=20012;
public static final Integer UPDATE_ERR=20013;
public static final Integer SELECT_ERR=20014;
public static final Integer SYSTEM_ERR=20031;
public static final Integer BUSINESS_ERR=20032;
}
自定义Controller返回结果类DataResult
package com.qwy.controller;
/**
* 该类用来封装Controller返回json的数据
*/
public class DataResult {
private Integer code;//封装状态码
private Object data;//封装真实的数据,这里必须为Object类型
private String message;//用来封装提示信息或异常信息等
public DataResult() {
}
public DataResult(Integer code, Object data) {
this.code = code;
this.data = data;
}
public DataResult(Integer code, Object data, String message) {
this.code = code;
this.data = data;
this.message = message;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
自定义业务异常处理类BusinessException
package com.qwy.exception;
import org.springframework.stereotype.Component;
/**
* 定义业务异常处理类
*/
public class BusinessException extends RuntimeException {
private Integer code;
public BusinessException(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;
}
}
自定义系统异常处理类SystemException
package com.qwy.exception;
import org.springframework.stereotype.Component;
/**
* 定义系统异常处理类
*/
public class SystemException extends RuntimeException {
private Integer code;
public SystemException( 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;
}
}
异常统一处理类ExceptionResultAdvice
package com.qwy.exception;
import com.qwy.controller.Code;
import com.qwy.controller.DataResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice//该注解表明该类为异常处理类
public class ExceptionResultAdvice {
@ExceptionHandler({SystemException.class})
public DataResult doSystemException(SystemException sx){
return new DataResult(Code.SYSTEM_ERR,null,sx.getMessage());
}
@ExceptionHandler({BusinessException.class})
public DataResult doBusinessException(BusinessException bx){
return new DataResult(Code.SYSTEM_ERR,null,bx.getMessage());
}
@ExceptionHandler({Exception.class})
public DataResult doException(Exception e){
return new DataResult(Code.SYSTEM_ERR,null,e.getMessage());
}
}
业务控制器处理类
package com.qwy.controller;
import com.qwy.bean.Users;
import com.qwy.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UsersController {
@Autowired
private UsersService usersService;
@PostMapping
public DataResult save(@RequestBody Users users){
boolean save = usersService.save(users);
return new DataResult(save?Code.SAVE_OK:Code.SAVE_ERR,save);
}
@DeleteMapping("/{id}")
public DataResult delete(@PathVariable("id") Integer id){
boolean delete = usersService.delete(id);
return new DataResult(delete?Code.DELETE_OK:Code.DELETE_ERR,delete);
}
@PutMapping
public DataResult update(@RequestBody Users users){
boolean update = usersService.update(users);
return new DataResult(update?Code.UPDATE_OK:Code.UPDATE_ERR,update);
}
@GetMapping("/{id}")
public DataResult findById(@PathVariable("id") Integer id){
Users users = usersService.findById(id);
Integer code = users != null ? Code.SELECT_OK : Code.SELECT_ERR;
String message = users != null ? "" : "查询失败,请重新查询";
return new DataResult(code,users,message);
}
@GetMapping
public DataResult findById(){
List<Users> usersList = usersService.findAll();
Integer code = usersList != null ? Code.SELECT_OK : Code.SELECT_ERR;
String message = usersList != null ? "" : "查询失败,请重新查询";
return new DataResult(code,usersList,message);
}
}