MyBatis简介
- JDBC操作数据库的封装,不再需要繁琐的 注册驱动 获得连接 执行sql语句的对象 准备sql 执行sql 关闭资源
MyBatis简易使用(使用框架)
具体操作
逆向工程
- generator.rarMyBatis资源生成
- 修改pom.xml里自己MySQL版本对应的依赖
- 修改generatorConfig.xml的
- MySQL版本对应的连接信息
- 指定实体类生成地址
- mapper映射文件生成的位置
- mapper接口生成的位置
- 指定数据库表
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><context id="testTables" targetRuntime="MyBatis3"><!-- JavaBean 实现 序列化 接口 --><plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin><!-- genenat entity时,生成toString --><plugin type="org.mybatis.generator.plugins.ToStringPlugin" /><!-- 共用5处要修改 --><!--修改1: 数据库连接的信息:驱动类、连接地址、用户名、密码 --><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/mall" userId="root"password="tarena"></jdbcConnection><!-- 数据库是8.0+时,1,修改pom.xml 加载mysql8的驱动 2,使用下面的jdbcConnection --><!--<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/mall" userId="root"password="root"><property name="useUnicode" value="true" /><property name="characterEncoding" value="utf-8" /><property name="serverTimezone" value="GMT" /><property name="nullCatalogMeansCurrent" value="true" /></jdbcConnection>--><!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL和 NUMERIC 类型解析为java.math.BigDecimal --><javaTypeResolver><property name="forceBigDecimals" value="false" /></javaTypeResolver><!--修改2: targetProject:生成PO实体类的位置 --><javaModelGeneratortargetPackage="com.haha.project_map.pojo"targetProject=".\src\main\java"><!-- enableSubPackages:是否让schema作为包的后缀 --><property name="enableSubPackages" value="false" /><!-- 从数据库返回的值被清理前后的空格 --><property name="trimStrings" value="true" /></javaModelGenerator><!--修改3: targetProject:mapper映射文件生成的位置 --><sqlMapGeneratortargetPackage="com.haha.project_map.mapper"targetProject=".\src\main\java"><!-- enableSubPackages:是否让schema作为包的后缀 --><property name="enableSubPackages" value="false" /></sqlMapGenerator><!-- 修改4: targetPackage:mapper接口生成的位置 --><javaClientGenerator type="XMLMAPPER"targetPackage="com.haha.project_map.mapper"targetProject=".\src\main\java"><!-- enableSubPackages:是否让schema作为包的后缀 --><property name="enableSubPackages" value="true" /></javaClientGenerator><!--修改5: 指定数据库表 --><table tableName="category" /><table tableName="item" /><table tableName="user" /><table tableName="jt_order" /><table tableName="admin" /></context></generatorConfiguration>
- 网站http://start.spring.io/生成初始化项目
- 添加依赖web,mysql,mybatis,后生成
- 逆向工程生成的包名要和 项目包名 一致 com.haha.project_map ,才能进行下面的复制com
- 导入项目到eclipse中,复制上面的mybatis资源com文件夹到本项目的src/mian/java/com文件夹
- 添加配置文件application.yml ,与数据库连接的相关信息
- 修改相应的地址:com.haha.project_map.mapper,这个可以从mapper下的 接口中 复制包路径
- 两处修改
- 连接数据库用户名,密码 ```java server: port: 8088
- 修改相应的地址:com.haha.project_map.mapper,这个可以从mapper下的 接口中 复制包路径
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
username: root
password: tarena
mybatis: mapperLocations: classpath:com.haha.project_map.mapper/*.xml
logging: path: ./logs level: com.haha.project_map.mapper: debug
- main所在的入口类上添加包扫描注解@mapperScan("com.haha.project_map.mapper")
- 通过MapperScan告诉框架给Mapper下的接口创建代理类Proxy51,为Proxy51类创建对象,放在spring ioc容器中
- 创建controller包,包下类UserController
- com.haha.project_map下面有包
- controller
- mapper
- 接口
- 抽象方法的定义
- 接口对应的xml
- sql语句的执行
- pojo
- 实体类
- 返回的结果类
- 实体Example类
- controller类中 查询条件类
```java
package com.haha.project_map.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.haha.project_map.mapper.UserMapper;
import com.haha.project_map.pojo.User;
@RestController
public class UserController {
//告诉框架给我分配对象
@Autowired
UserMapper userMapper;
//选择全部
//selectByExample表示条件查询,设置参数为null,就是全部不设置条件,全部查出来
@RequestMapping("/selectAll")
public List<User> selectAll() {
return userMapper.selectByExample(null);
}
//选择升序查询
//setOrderByClause设置条件参数 user_id升序
@RequestMapping("/asc")
public List<User> asc(){
//创建example对象,并调用方法生成排序后的结果
UserExample userExample = new UserExample();
userExample.setOrderByClause("user_id asc");
List<User> list = userMapper.selectByExample(userExample);
return list;
}
//选择降序查询
//setOrderByClause设置条件查询参数 user_id降序
@RequestMapping("/desc")
public List<User> desc(){
//创建example对象,并调用方法生成排序后的结果
UserExample userExample = new UserExample();
userExample.setOrderByClause("user_id desc");
List<User> list = userMapper.selectByExample(userExample);
return list;
}
//登录
//criteria是UserExample的内部类,想用criteria的比较方法andUsernameEqualTo,criteria表示查询中where
//criteria相当于是UserExample的条件查询参数
@RequestMapping("/login")
public User login(String username,String password) {
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.or();
criteria.andUsernameEqualTo(username);
criteria.andPasswordEqualTo(password);
List<User> list = userMapper.selectByExample(userExample);
return list.get(0);
}
//插入
@RequestMapping("/insert")
public Integer insert(String username,String password) {
//创建对象
User user = new User();
user.setUsername(username);
user.setPassword(password);
//把对象传给mybatis框架,框架生成insert语句
int count=userMapper.insert(user);
return count;
}
//更新
//根据主键更新用户名、密码
@RequestMapping("/update")
public Integer update(Integer userId,String username,String password) {
User user = new User();
user.setUserId(userId);
user.setUsername(username);
user.setPassword(password);
int count = userMapper.updateByPrimaryKey(user);
return count;
}
//删除
//根据主键删除记录
@RequestMapping("/delete")
public Integer delete(Integer userId) {
int count = userMapper.deleteByPrimaryKey(userId);
return count;
}
//修改密码
//修改密码用更新操作,传入的UserExample就是更新的条件
@RequestMapping("/changePassword")
public Integer changePassword(String oldUsername,String oldPassword,String newPassword) {
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.or();
criteria.andUsernameEqualTo(oldUsername);
criteria.andPasswordEqualTo(oldPassword);
User user = new User();
user.setPassword(newPassword);
int count = userMapper.updateByExampleSelective(user, userExample);
return count;
}
}
Mybatis是一个数据库框架
- 封装了连接,sql的执行,结果集转换
总结使用步骤
1, 使用generater项目生成.xml,接口,pojo,example
2, 创建springboot项目,依赖web,mybatis,mysql driver
3, 配置application.yml,配置数据库信息,xml的位置,log
4, Applicatoin 添置@mapperScan(“mapper包名”),mybatis框加会为包下的每个接口创建代理对象。
5, Controller通过autowired从spring容器中取对象
6, 对象有insert(),delete(),update(),查询用example,criteria
总结使用方法
- example
- 条件查询,如排序等
- Criteria是example的内部类,用于where语句的比较
- 方法选择上,能用selecttive的方法就用它
- selecttive不会更新你没有赋的值
- 一般是根据primarykey操作,有条件的就使用exaple方法

