Springboot-整合MyBatis操作
整合MyBatis操作
https://github.com/mybatis
mybatis官方文档:
https://mybatis.org/mybatis-3/zh/index.html
starter
SpringBoot官方的Starter:spring-boot-starter-*
第三方的: *-spring-boot-starter
引入依赖
pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
1、配置模式
• 全局配置文件
• SqlSessionFactory: 自动配置好了
• SqlSession:自动配置了 SqlSessionTemplate 组合了SqlSession
• @Import(AutoConfiguredMapperScannerRegistrar.class);
• Mapper: 只要我们写的操作MyBatis的接口标准了 @Mapper 就会被自动扫描进来
@EnableConfigurationProperties(MybatisProperties.class) : MyBatis配置项绑定类。
@AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
public class MybatisAutoConfiguration{}
@ConfigurationProperties(prefix = “mybatis”)
public class MybatisProperties
可以修改配置文件中 mybatis 开始的所有;
配置mybatis规则
yaml文件:
#配置mybatis规则
mybatis:
#config-location: classpath:mybatis/mybatis-config.xml #mybatis全局配置文件位置
mapper-locations: classpath:mybatis/mapper/*.xml #sql映射文件位置
configuration: #指定mybatis全局配置文件中的相关配置项
map-underscore-to-camel-case: true #由于全局配置文件只能有一个,所以这个和config-location只能选择其中一个
Mapper接口—>绑定Xml
StudentMapper.xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zm.admin.mapper.StudentMapper">
<select id="getStu" resultType="com.zm.admin.bean.Student">
select * from student where usernumber=#{userid}
</select>
</mapper>
配置 private Configuration configuration; mybatis.configuration下面的所有,就是相当于改mybatis全局配置文件中的值
配置mybatis规则
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
configuration:
map-underscore-to-camel-case: true
可以不写全局;配置文件,所有全局配置文件的配置都放在configuration配置项中即可
• 导入mybatis官方starter
• 编写mapper接口。标准@Mapper注解
• 编写sql映射文件并绑定mapper接口
• 在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息 (建议;配置在mybatis.configuration标签下)
实例:
Student.java
package com.zm.admin.bean;
import lombok.Data;
@Data
public class Student {
private Long usernumber;
private String name;
private String sex;
private Integer age;
}
StudentMapper.java
package com.zm.admin.mapper;
import com.zm.admin.bean.Student;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StudentMapper {
public Student getStu(Long userid);
}
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- <settings>-->
<!-- <setting name="mapUnderscoreToCamelCase" value="true"/> <!– 开启驼峰规则 –>-->
<!-- </settings>-->
</configuration>
StudentService.java
package com.zm.admin.service;
import com.zm.admin.bean.Student;
import com.zm.admin.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
@Autowired
StudentMapper studentMapper;
public Student getStuByuserid(Long userid){
return studentMapper.getStu(userid);
}
}
MybatisController.java
package com.zm.admin.controller;
import com.zm.admin.bean.Student;
import com.zm.admin.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MybatisController {
@Autowired
StudentService studentService;
@ResponseBody
@GetMapping("/stu")
public Student getByUserid(@RequestParam("userid") long userid){
return studentService.getStuByuserid(userid);
}
}
StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zm.admin.mapper.StudentMapper">
<select id="getStu" resultType="com.zm.admin.bean.Student">
select * from student where usernumber=#{userid}
</select>
</mapper>
2、注解模式
@Mapper
public interface CityMapper {
@Select("select * from city where id=#{id}")
public City getById(Long id);
}
3、混合模式
@Mapper
public interface CityMapper {
@Select("select * from city where id=#{id}")
public City getById(Long id);
public void insert(City city);
}
最佳实战:
• 引入mybatis-starter
• 配置application.yaml中,指定mapper-location位置即可
• 编写Mapper接口并标注@Mapper注解
• 简单方法直接注解方式
• 复杂方法编写mapper.xml进行绑定映射
• @MapperScan(“com.atguigu.admin.mapper”) 简化,其他的接口就可以不用标注@Mapper注解
实例:
City.java
package com.zm.admin.bean;
import lombok.Data;
@Data
public class City {
private Long id;
private String name;
private String state;
private String country;
}
CityMapper.java
package com.zm.admin.mapper;
import com.zm.admin.bean.City;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface CityMapper {
@Select("select * from city where id=#{id}")
public City getById(Long id);
public void insert(City city); //需要绑定Mapper的配置文件
}
CityService.java
package com.zm.admin.service;
import com.zm.admin.bean.City;
import com.zm.admin.mapper.CityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CityService {
@Autowired
CityMapper cityMapper;
public City getById(Long id){
return cityMapper.getById(id);
}
public void saveCity(City city) {
cityMapper.insert(city);
}
}
CityMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zm.admin.mapper.StudentMapper">
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into city(`name`,`state`,`country`) values(#{city},#{state},#{country})
</insert>
</mapper>
MybatisController.java
package com.zm.admin.controller;
import com.zm.admin.bean.City;
import com.zm.admin.bean.Student;
import com.zm.admin.mapper.CityMapper;
import com.zm.admin.service.CityService;
import com.zm.admin.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MybatisController {
@Autowired
CityService cityService;
@ResponseBody
@GetMapping("/city")
public City getCityById(@RequestParam("id") long id){
return cityService.getById(id);
}
@ResponseBody
@PostMapping("/insertcity")
public City saveCity(City city){
cityService.saveCity(city);
return city;
}
}
4、整合 MyBatis-Plus 完成CRUD
1、什么是MyBatis-Plus
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
mybatis plus 官网:https://baomidou.com/guide/
建议安装 MybatisX 插件
2、整合MyBatis-Plus
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
自动配置
• MybatisPlusAutoConfiguration 配置类,MybatisPlusProperties 配置项绑定。mybatis-plus:xxx 就是对mybatis-plus的定制
• SqlSessionFactory 自动配置好。底层是容器中默认的数据源
• mapperLocations 自动配置好的。有默认值。classpath*:/mapper/**/*.xml;任意包的类路径下的所有mapper文件夹下任意路径下的所有xml都是sql映射文件。 建议以后sql映射文件,放在 mapper下
• 容器中也自动配置好了 SqlSessionTemplate
• @Mapper 标注的接口也会被自动扫描;建议直接 @MapperScan(“com.atguigu.admin.mapper”) 批量扫描就行
优点:
• 只需要我们的Mapper继承 BaseMapper 就可以拥有crud能力
3、CRUD功能
实例:
TableController.java
package com.zm.admin.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zm.admin.bean.User;
import com.zm.admin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.Arrays;
import java.util.List;
@Controller
public class TableController {
@Autowired
UserService userService;
@GetMapping("/user/delete/{id}")
public String deleteUser(@PathVariable("id") Long id,
@RequestParam(value = "pn",defaultValue = "1") Integer pn,
RedirectAttributes ra){
userService.removeById(id);
ra.addAttribute("pn",pn);
return "redirect:/dynamic_table";
}
@GetMapping("/dynamic_table")
public String dynamic_table(@RequestParam(value = "pn",defaultValue = "1") Integer pn, Model model){ //向表单提供动态数据
//从数据库中查出user表中的用户进行展示
// List<User> list=userService.list();
//model.addAttribute("users",list);
//分页查询数据
//构造分页参数
Page<User> page= new Page<User>(pn,3); //3是指当前页面显示多少条记录
//分页查询的结果
Page<User> userPage=userService.page(page,null);
// long current=page.getCurrent(); //当前多少页
// long pages=page.getPages(); //总共多少页
// long total=page.getTotal();//总共多少条记录
// List<User> records= page.getRecords();
model.addAttribute("users",userPage);
return "table/dynamic_table";
}
}
MyBatisConfig.java //分页
package com.zm.admin.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisConfig {
@Bean
public MybatisPlusInterceptor paginationInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor=new MybatisPlusInterceptor();
//这是分页拦截器
PaginationInnerInterceptor paginationInnerInterceptor=new PaginationInnerInterceptor();
paginationInnerInterceptor.setOverflow(true); //设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
paginationInnerInterceptor.setMaxLimit(50L); //设置最大单页限制数量,默认 500 条,-1 不受限制
mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
return mybatisPlusInterceptor;
}
}
dynamic_table.html
<table class="display table table-bordered table-striped" id="dynamic-table">
<thead>
<tr>
<th>#</th>
<th>id</th>
<th>name</th>
<th>age</th>
<th>email</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr class="gradeX" th:each="user,stat:${users.records}"> <!--遍历users中的对象-->
<td th:text="${stat.count}"></td>
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
<td>[[${user.email}]]</td>
<td>
<a th:href="@{/user/delete/{id}(id=${user.id},pn=${users.current})}" class="btn btn-danger btn-sm" type="button">删除</a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>#</th>
<th>id</th>
<th>name</th>
<th>age</th>
<th>email</th>
<th>操作</th>
</tr>
</tfoot>
</table>
<div class="row-fluid">
<div class="span6">
<div class="dataTables_info" id="dynamic-table_info">当前第[[${users.current}]]页
总计[[${users.pages}]]页 共[[${users.total}]]条记录</div>
</div>
<div class="span6">
<div class="dataTables_paginate paging_bootstrap pagination">
<ul>
<li class="prev disabled"><a href="#">← Previous</a></li>
<li th:class="${num==users.current?'active':''}" th:each="num:${#numbers.sequence(1,users.pages)}">
<a th:href="@{/dynamic_table(pn=${num})}">[[${num}]]</a></li>
<li class="next"><a href="#">Next → </a></li>
</ul>
</div>
</div>
</div>