目录
整合Mybatis
整合Mybatis-plus
整合Druid
自定义方式
引入starter方式
整合PageHelper
统一返回对象类型
使用枚举类型改进
整合Mybatis
1、引入mybatis启动器、mysql驱动
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency>
2、配置文件设置参数信息
如果配置内容比较多,单独做一个配置文件并指定位置
mybatis.config-location=mybatis-config.xml
3、设置JavaBean,Mapper接口,并生成xml文件,再生成方法,sql需要自己写
5、必须在dao接口加上@Mapper或在启动类加上@MapperScan指明路径,注入到容器
整合Mybatis-plus
1、依赖包含mybatis、mysql
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.3</version> </dependency>
2、配置文件设置参数信息
3、使用德鲁伊数据源
@Configuration public class DruidDataSourceConfig {@ConfigurationProperties("spring.datasource")@Beanpublic DataSource dataSource() throws SQLException {DruidDataSource druidDataSource =new DruidDataSource();return druidDataSource;} }
3、设置JavaBean:Monster
Mapper层接口继承BaseMapper<>
BaseMapper默认提供了很多curd方法,可以直接使用,也可以自定义方法
@Mapper public interface MonsterMapper extends BaseMapper<Monster> {}
Service层接口实现IService
public interface MonsterService extends IService<Monster> {}
Service层实现类,继承ServiceImpl实现Service接口
@Service public class MonsterServiceImplextends ServiceImpl<MonsterMapper, Mapper>implements MonsterService {}
整合Druid
自定义方式
1、修改pom.xml,引入druid依赖
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.23</version> </dependency>
2、创建配置类,如果没有dataSource配置,默认是HikanDataSource
开启Durid监控功能
原本是web.xml文件配置,现在使用配置类
import com.alibaba.druid.support.jakarta.StatViewServlet;
import com.alibaba.druid.support.jakarta.WebStatFilter;@Configuration public class Druid {@ConfigurationProperties("spring.datasource")@Beanpublic DataSource dataSource() throws SQLException {DruidDataSource druidDataSource = new DruidDataSource();//加入监控功能, 加入sql防火墙监控//set用来设置DataSource的属性,类似name-valuedruidDataSource.setFilters("stat,wall");return druidDataSource;}//配置druid的监控页功能@Beanpublic ServletRegistrationBean statViewServlet() {StatViewServlet statViewServlet = new StatViewServlet();ServletRegistrationBean<StatViewServlet> servletRegistrationBean =// druid监控的访问页面是/druid/*//配置好之后,访问/druid下的地址的时候都会先登录new ServletRegistrationBean<>(statViewServlet, "/druid/*");// 开启监控页面的访问登录账号和密码servletRegistrationBean.addInitParameter("loginUsername", "druid");servletRegistrationBean.addInitParameter("loginPassword", "123456");return servletRegistrationBean;}//配置WebStatFilter, 用于采集web-jdbc关联的监控数据@Beanpublic FilterRegistrationBean webStatFilter() {WebStatFilter webStatFilter = new WebStatFilter();FilterRegistrationBean<WebStatFilter> filterRegistrationBean =new FilterRegistrationBean<>(webStatFilter);//默认对所有的url请求进行监控filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));//排除指定的urlfilterRegistrationBean.addInitParameter ("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");return filterRegistrationBean;} }
引入starter方式
去掉druid的依赖和配置类,引入druid strater和application.yml
<dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.15</version></dependency>
spring:datasource:url: jdbc:mysql://localhost:3306/spring_boot?useSSL=true&useUnicode=true&characterEncoding=UTF-8username: rootpassword: 123456driver-class-name: com.mysql.jdbc.Driver#配置druid和监控功能druid:stat-view-servlet:enable: truelogin-username: jacklogin-password: 666reset-enable: false#配置web监控web-stat-filter:enable: trueurl-pattern: /*exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
整合PageHelper
1、引入依赖
<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>2.1.0</version> </dependency>
2、编写代码
Constant自己设置常量类
@RestController public class VipController {@Autowiredprivate VipService vipService;@GetMapping("/list/{pageNo}")public PageInfo<Vip> list(@PathVariable("pageNo") Integer pageNo) {// 1.设置当前页码和每页显示的记录条数PageHelper.startPage(pageNo, Constant.PAGE_SIZE);// 2.获取数据(PageHelper会自动给SQL语句添加limit)List<Vip> vips = vipService.findAll();// 3.将分页数据封装到PageInfoPageInfo<Vip> vipPageInfo = new PageInfo<>(vips);return vipPageInfo;} }
统一返回对象类型
适用于前后端分离系统,thymeleaf不能用
Result<PageInfo<Vip>> Result<Vip>
public class Result<T> {private String code;private String msg;private T data;public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public T getData() {return data;}public void setData(T data) {this.data = data;}public Result() {}public Result(T data) {this.data = data;}public static Result success() {Result result = new Result<>();result.setCode("200");result.setMsg("success");return result;}//携带数据public static <T> Result<T> success(T data) {Result<T> result = new Result<>(data);result.setCode("200");result.setMsg("success");return result;}//失败有多种原因,状态码也不同,所以要有形参public static Result error(String code, String msg) {Result result = new Result();result.setCode(code);result.setMsg(msg);return result;}public static <T> Result<T> error(String code, String msg, T data) {Result<T> result = new Result<>(data);result.setCode(code);result.setMsg(msg);return result;}
}
@RestController
public class VipController {@Autowiredprivate VipService vipService;@GetMapping("/list/{pageNo}")public Result<PageInfo<Vip>> list(@PathVariable("pageNo") Integer pageNo) {// 1.设置当前页码和每页显示的记录条数PageHelper.startPage(pageNo, Constant.PAGE_SIZE);// 2.获取数据(PageHelper会自动给SQL语句添加limit)List<Vip> vips = vipService.findAll();// 3.将分页数据封装到PageInfoPageInfo<Vip> vipPageInfo = new PageInfo<>(vips);return Result.success(vipPageInfo);}
}
使用枚举类型改进
@NoArgsConstructor
@AllArgsConstructor
public enum CodeEnum {OK(200, "成功"),FAIL(400, "失败"),BAD_REQUEST(400, "请求错误"),NOT_FOUND(404, "未找到资源"),INTERNAL_ERROR(500, "内部服务器错误"),MODIFICATION_FAILED(400, "修改失败"),DELETION_FAILED(400, "删除失败"),CREATION_FAILED(400, "创建失败");@Getter@Setterprivate int code;@Getter@Setterprivate String msg;}
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class R<T> {private int code; // 响应的状态码private String msg; // 响应的消息private T data; // 响应的数据体// 用于构建成功的响应,不携带数据public static <T> R<T> OK() {return R.<T>builder().code(CodeEnum.OK.getCode()).msg(CodeEnum.OK.getMsg()).build();}// 用于构建成功的响应,携带数据public static <T> R<T> OK(T data) {return R.<T>builder().code(CodeEnum.OK.getCode()).msg(CodeEnum.OK.getMsg()).data(data).build();}// 用于构建失败的响应,不带任何参数,默认状态码为400,消息为"失败"public static <T> R<T> FAIL() {return R.<T>builder().code(CodeEnum.FAIL.getCode()).msg(CodeEnum.FAIL.getMsg()).build();}// 用于构建失败的响应,自定义状态码和消息public static <T> R<T> FAIL(CodeEnum codeEnum) {return R.<T>builder().code(codeEnum.getCode()).msg(codeEnum.getMsg()).build();}
}