目录
一、整合MyBatis操作
1、配置模式
2、注解模式
3、混合模式
二、整合 MyBatis-Plus 完成CRUD
1、什么是MyBatis-Plus
2、整合MyBatis-Plus
3、CRUD功能
官网:MyBatis · GitHub
SpringBoot官方的Starter:spring-boot-starter-*
第三方的starter的格式: *-spring-boot-starter
org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.4

@EnableConfigurationProperties(MybatisProperties.class) : MyBatis配置项绑定类。
@AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
public class MybatisAutoConfiguration{}@ConfigurationProperties(prefix = "mybatis")
public class MybatisProperties
# 配置mybatis规则
mybatis:config-location: classpath:mybatis/mybatis-config.xml #全局配置文件位置mapper-locations: classpath:mybatis/mapper/*.xml #sql映射文件位置Mapper接口--->绑定Xml
配置 private Configuration configuration; mybatis.configuration下面的所有,就是相当于改mybatis全局配置文件中的值
# 配置mybatis规则
mybatis:
# config-location: classpath:mybatis/mybatis-config.xmlmapper-locations: classpath:mybatis/mapper/*.xmlconfiguration:map-underscore-to-camel-case: true可以不写全局;配置文件,所有全局配置文件的配置都放在configuration配置项中即可
@Mapper
public interface CityMapper {@Select("select * from city where id=#{id}")public City getById(Long id);public void insert(City city);}
@Mapper
public interface CityMapper {@Select("select * from city where id=#{id}")public City getById(Long id);//绑定在mapper映射文件中public void insert(City city);}
总结:
- 引入mybatis-starter
- 配置application.yaml中,指定mapper-location位置即可
- 编写Mapper接口并标注@Mapper注解
- 简单方法直接注解方式
- 复杂方法编写mapper.xml进行绑定映射
- @MapperScan("com.atguigu.admin.mapper") 简化,其他的接口就可以不用标注@Mapper注解
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
mybatis plus 官网
建议安装 MybatisX 插件
com.baomidou mybatis-plus-boot-starter 3.4.1
自动配置
优点:
@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){//表格内容的遍历
// response.sendError
// List users = Arrays.asList(new User("zhangsan", "123456"),
// new User("lisi", "123444"),
// new User("haha", "aaaaa"),
// new User("hehe ", "aaddd"));
// model.addAttribute("users",users);
//
// if(users.size()>3){
// throw new UserTooManyException();
// }//从数据库中查出user表中的用户进行展示//构造分页参数Page page = new Page<>(pn, 2);//调用page进行分页Page userPage = userService.page(page, null);// userPage.getRecords()
// userPage.getCurrent()
// userPage.getPages()model.addAttribute("users",userPage);return "table/dynamic_table";}
Service
@Service
public class UserServiceImpl extends ServiceImpl implements UserService {}public interface UserService extends IService {}