springboot-入门2

1.静态资源

当访问项目中的任意资源(即“/**”)时,Spring Boot 会默认从以下路径中查找资源文件(优先级依次降低):

classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public/

这些路径又被称为静态资源文件夹,它们的优先级顺序为:classpath:/META-INF/resources/ > classpath:/resources/ > classpath:/static/ > classpath:/public/ 。

当我们请求某个静态资源(即以“.html”结尾的请求)时,Spring Boot 会先查找优先级高的文件夹,再查找优先级低的文件夹,直到找到指定的静态资源为止。

支持自定义

spring.web.resources.static-locations=file:${upload.url}upload.url=d:/pic/

2.拦截器

通过实现WebMvcConfigurer接口 并添加@Configuration注解来实现自定义部分SpringMvc配置。

2.1 创建自定义拦截器

@Componentpublic class MyInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("我是拦截器");return true;}}

2.2 注册拦截器

@Configurationpublic class SpringConfig implements WebMvcConfigurer {@AutowiredMyInterceptor myInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(myInterceptor).addPathPatterns("/**").excludePathPatterns("/static/**","/login/**","/logout/**");}}

3.Spring Boot集成MyBatis

3.1 添加依赖

org.mybatis.spring.bootmybatis-spring-boot-starter2.1.1mysqlmysql-connector-java5.1.49

3.2 配置application.properties

mybatis.mapper-locations=classpath:mappers/*.xmlspring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql:///2004A?useUnicode=true&characterEncoding=utf-8spring.datasource.username=rootspring.datasource.password=rootmybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

3.3 创建接口

@Mapperpublic interface UserMapper {List list();}

3.4 创建映射文件

3.5 测试

4.springboot集成mybatis-plus

4.1 简介

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

官网:https://baomidou.com/

4.2 数据准备

DROP TABLE IF EXISTS user;CREATE TABLE user(id BIGINT(20) NOT NULL COMMENT '主键ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',age INT(11) NULL DEFAULT NULL COMMENT '年龄',email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',PRIMARY KEY (id));
DELETE FROM user;INSERT INTO user (id, name, age, email) VALUES(1, 'Jone', 18, 'test1@baomidou.com'),(2, 'Jack', 20, 'test2@baomidou.com'),(3, 'Tom', 28, 'test3@baomidou.com'),(4, 'Sandy', 21, 'test4@baomidou.com'),(5, 'Billie', 24, 'test5@baomidou.com');

4.4 实体类

@Datapublic class User {private Long id;private String name;private Integer age;private String email;}

4.5 添加依赖

com.baomidoumybatis-plus-boot-starter3.5.1mysqlmysql-connector-java5.1.49

4.6 基础使用

4.6.0 数据库基础信息

spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql:///2004A-plus?useUnicode=true&characterEncoding=utf-8spring.datasource.username=rootspring.datasource.password=rootmybatis-plus.mapper-locations=classpath:mappers/*.xmlmybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

4.6.1 接口

public interface UserMapper extends BaseMapper {}

4.6.2 简单crud测试

@Testpublic void testSelect(){//查询所有List userList = userMapper.selectList(null);userList.forEach(System.out::println);}@Testpublic void testAdd(){//添加userMapper.insert(new User(6l,"唐僧",23,"tangceng@qq.com"));}@Testpublic void testDel(){//删除方式1int i = userMapper.deleteById(6l);System.out.println("删除影响的行数:"+i);}@Testpublic void testUpdate(){userMapper.updateById(new User(6l,"八戒",21,"八戒@qq.com"));}

4.6.3 相关注解

https://baomidou.com/pages/223848/#tablename

参考官网

4.7复杂查询

4.7.1 条件查询

案例1:

查询名字包含 a 年龄在20-30 之间 邮箱不为空的数据

@Testpublic void testSelect2(){QueryWrapper queryWrapper = new QueryWrapper<>();queryWrapper.like("name", "a").gt("age", 20).lt("age", 30).isNotNull("email");List users = userMapper.selectList(queryWrapper);users.forEach(System.out::println);}

案例2:lambda表达式的查询

查询名字包含 a 年龄在20-30 之间 邮箱不为空的数据

@Testpublic void testSelect3(){LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();queryWrapper.like(User::getName, "a").gt(User::getAge, 20).lt(User::getAge, 30).isNotNull(User::getEmail);List users = userMapper.selectList(queryWrapper);users.forEach(System.out::println);}

案例3 动态条件查询

@Testpublic void testSelect4(){//查询名字包含 a 年龄在20-30 之间 邮箱不为空的数据QueryWrapper queryWrapper = new QueryWrapper<>();//动态条件拼接String name="";Integer ageBegin =20;Integer ageEnd =30;queryWrapper.like(StringUtils.isNotBlank(name),"name",name).gt(ageBegin!=null,"age",ageBegin).lt(ageEnd!=null,"age",ageEnd);List users = userMapper.selectList(queryWrapper);users.forEach(System.out::println);}

案例4带分页查询

4.8分页插件

4.8.1配置分页插件

@Configuration@MapperScan("com.bobo.demo.mapper")public class MybatisConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)) ;return interceptor;}}

4.8.2 使用

@Testpublic void testSelect5(){//查询名字包含 a 年龄在20-30 之间 邮箱不为空的数据QueryWrapper queryWrapper = new QueryWrapper<>();//动态条件拼接String name="";Integer ageBegin =20;Integer ageEnd =30;queryWrapper.like(StringUtils.isNotBlank(name),"name",name).gt(ageBegin!=null,"age",ageBegin).lt(ageEnd!=null,"age",ageEnd);Page page = new Page<>(1,3);page = userMapper.selectPage(page,queryWrapper);List list = page.getRecords();System.out.println(list);}

4.9 通用servcie

  • 通用 Service CRUD 封装IService (opens new window)接口,进一步封装 CRUD 采用 get 查询单行 remove 删除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆,
  • 泛型 T 为任意实体对象
  • 建议如果存在自定义通用 Service 方法的可能,请创建自己的 IBaseService 继承 Mybatis-Plus 提供的基类
  • 对象 Wrapper 为 条件构造器

4.9.1 一般开发

接口

public interface UserService extends IService {}

实现类

@Servicepublic class UserServiceImpl extends ServiceImpl implements UserService {}

测试:

public void testAddorUpdate(){//有id执行修改,没有id执行增加User user = new User(7l, "沙僧", 21, "bajie@qq.com");userService.saveOrUpdate(user);}

4.10 mybatisx插件

https://baomidou.com/pages/ba5b24/#%E5%8A%9F%E8%83%BD

MybatisX 是一款基于 IDEA 的快速开发插件,为效率而生。

安装方法:打开 IDEA,进入 File -> Settings -> Plugins -> Browse Repositories,输入 mybatisx 搜索并安装。

4.10.1 安装

4.10.2 配置数据源连接

第一步:

第二步:

第三步: 选择表

第四步:

第五步

第六步 效果

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章