Spring boot 整合mybatis
1. 引入依赖
<!--mybatis的依赖--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency>
2. 配置mybatis
2.1 配置数据库连接
spring: datasource: url: jdbc:mysql://127.0.0.1:3306/ssm username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver
2.2 配置mybatis
mybatis: # 配置别名的包地址 type-aliases-package: com.tledu.springbootmybatis.domain # 配置mapper xml的地址 mapper-locations: classpath:com/tledu/springbootmybatis/dao/*.xml
2.3 开启mapper扫描
目的:把对应mybatis的mapper的实例放到spring容器中
在spring启动类中配置
@MapperScan(basePackages = "com.tledu.springbootmybatis.dao")
2.4 开发dao层即可
3. spring boot 配置方法
3.1 使用@Mapper
在spring boot的项目中我们也可以不配置@MapperScan。 可以通过@Mapper注解的方法,把mapper实例放到spring容器中。
@Mapper public interface UserDao { List<User> list(); }
3.2 可以xml放到resource目录下
很多开发者习惯将xml放到resource。
mybatis: # 配置别名的包地址 type-aliases-package: com.tledu.springbootmybatis.domain # 配置mapper xml的地址 #mapper-locations: classpath:com/tledu/springbootmybatis/dao/*.xml # 加载resource中mapper目录下所有的xml文件 mapper-locations: classpath:mapper/*.xml configuration: map-underscore-to-camel-case: true #开启数据库字段与实体类映射 user_name->userName
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources>
3.3 如果需要引入mybatis配置文件的时候
在resource目录中创建一个mybatis的配置文件,在application.yml声明它的路径
mybatis: # 配置本地文件 config-location: classpath:mybatis/mybatis-config.xml
3.4 日志配置
spring boot内置日志,可以直接配置日志打印级别,让spring boot打印sql语句
logging: level: com.tledu: debug
3.5 连接池
3.5.1 引入依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.17</version> </dependency>
3.5.2 连接池配置
spring: datasource: url: jdbc:mysql://127.0.0.1:3306/springboot_study username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource druid: max-active: 20 min-idle: 10 useGlobalDataSourceStat: true # 设置过滤的日志 filters: stat,wall,1og4j web-stat-filter: enabled: true url-pattern: /** stat-view-servlet: enabled: true login-username: admin login-password: admin allow: 127.0.0.1 filter: wall: config: multi-statement-allow: true
spring boot3
一、课程纪实
- 模板引擎中th:onclick的使用
- 通过拦截器实现静态资源拦截,完成登录功能
- thymeleaf模板引擎实现引用
- mybatis plus的使用
- 项目分组介绍
二、知识点
1. 模板引擎中onclick的使用
如果需要使用th:onclick,这个时候我们需要把代码用||包裹起来,之后在||里面就可以添加表达式了如${},或者@{}。
1.1 获取地址参数、number类型或者bool类型参数
这类参数可以直接通过表达式获取
<button class="layui-btn" th:οnclick="|xadmin.open('添加用户','@{/user/add}',600,400)|"> 添加 </button>
1.2 对于其他类型的参数
thymeleaf为了防止js脚本注入,对于非number、bool类型的参数是不信任的,这里如果我们希望加载这类型的参数可以通过data-*来设置和获取
<!-- data-* : 作用是为了设置标签上自定参数 this触发点击事件的dom对象,this.getAttribute("data-title") --> <button id="addBtn" th:data-title="${title}" data-id="主键" class="layui-btn" th:οnclick="|xadmin.open(this.dataset.title,'@{/user/add}',600,400)|"><i class="layui-icon"></i>添加 </button>
1.3 data-*
每个html标签上可以通过data-*设置标签自定义参数,如果我们希望给标签添加一个title指定参数,可以data-title=""进行设置
获取data-参数:
- dom对象 .dataset.参数名
- dom对象.getAttrbute("data-参数名")
- jquery对象.data("参数名")
2. 添加拦截器
2.1 编写拦截器
/** * @author mark */ public class AuthInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // hanlder就是Controller和对应method HandlerMethod handlerMethod = (HandlerMethod) handler; // true代表如果没有session就会创建一个session,false没有session就会返回null HttpSession session = request.getSession(true); User user = (User) session.getAttribute(CommonConstants.LOGIN_USER_SESSION_KEY); if (user == null) { // 代表没有登录 response.sendRedirect(request.getContextPath() + "/login"); // 终止后续请求 return false; } return super.preHandle(request, response, handler); } }
2.2 注册拦截器
@Configuration public class WebAppConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //注册自己的拦截器并设置拦截的请求路径 registry.addInterceptor(new AuthInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/login"); } }
3 thymeleaf模板引擎实现引用
3.1 通过th:fragment="header" 定义待引用的模块
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>包含</title> </head> <body> <div th:fragment="header"> <div>头部</div> </div> </body> </html>
3.2 通过th:replace 和 th:include进行引用
<div th:replace="include::header"></div> <div th:include="include::header"></div>
3.3 replace和include的区别
<span th:fragment="content"> 一行代码 </span>
replace
<div th:replace="include/include::content"> 13123 </div>
会用标签替换掉当前的标签,最终渲染出来内容如下
<span> 一行代码 </span>
include
<div th:include="include/include::content"> 13123 </div>
会把对应标签里面的内容,放在当前标签的内容里面,最终渲染出来
<div> 一行代码 </div>
3.4 th:block
th:block是模板引擎提供的一个标签,这个标签本身没有任何含义,只是为了让我们写命令。最终渲染的时候会被删除掉
<th:block th:include="include/include::header" />
4. js中获取上下文
var ctx = [[${#httpServletRequest.getContextPath()}]]; /*<![CDATA[*/ var ctx = /*[[@{/}]]*/ ''; /*]]>*/
5 分页
1. 引入依赖
<!--pagehelper--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency>
2. 添加配置文件
# 分页配置 pagehelper: helper-dialect: mysql reasonable: true support-methods-arguments: true params: count=countSql
3. 使用插件
@Test public void testList() throws IOException { SqlSession session = MybatisUtils.openSession(); User condition = new User(); // 插件里提供的分页工具,在要查询之前,执行一下PageHelper.startPage(当前页数,每页的容量), 当使用工具时候,会导致懒加载失败 // 加了这个操作,插件就会在sql语句中拼接limit限制,并且还会统计总个数 PageHelper.startPage(1,5); List<User> users = session.getMapper(IUserMapper.class).list(condition); // 拿到结果之后通过PageInfo.of() 的方法,获得pageInfo com.github.pagehelper.PageInfo<User> list = com.github.pagehelper.PageInfo.of(users); System.out.println(users); }
6. mybatis plus
快速开始
- 引入依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency>
2.集成BaseMapper在service实现类中调用被继承的list方法
@Mapper public interface AddressMapper extends BaseMapper<Address> { }
@Service @AllArgsConstructor public class AddressServiceImpl implements IAddressService { private AddressMapper addressMapper; @Override public List<Address> list() { QueryWrapper<Address> queryWrapper = new QueryWrapper<>(); return addressMapper.selectList(queryWrapper); }
3.配置mybatis plus 别名
mybatis-plus: type-aliases-package: com.tledu.springbootmybatis.domain
- 配置实体类
@Data @TableName("t_address") public class Address { @TableId(type=IdType.AUTO) private Integer id; private String addr; private String phone; @TableField("user_id") private Integer userId; }
- 使用mybatis plus的方法了
@RunWith(SpringRunner.class) @SpringBootTest public class MybatisPlusTest { @Autowired private UserDao userDao; @Test public void save() { // User user = new User(); // user.setUsername("test"); // user.setPassword("999"); // userDao.insert(user); /** * 1. 别名不能用了 * 2. 插入操作的时候,mybatis plus会生成一个唯一id,这个类型和表的类型不一致 * 3. 查询操作的时候,生成的查询语句的表名是按照user生成的,并不是t_user */ QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.like("username", "admin"); queryWrapper.lambda().eq(User::getPassword, "root"); queryWrapper.select("username"); List<User> list = userDao.selectList(queryWrapper); System.out.println(list); } }