- 重启mysql服务(cmd)
- 持久化框架
- 初始demo
- 日志输出
- CRUD
- 插入
- 更新
- 删除
- 查询
- ActiveRecord(AR)
- idType
- 逻辑删除
- 自定义唯一id生成器
- 自定义表名
- 自定义列名
- 自定义sql语句
- 自动填充
- 乐观锁
- Wrapper类
- QueryWrapper
- allEq
- eq
- ne
- gt
- ge
- lt
- le
- between
- notBetween
- like
- notLIke
- leftLike和likeRight
- isNull和isNotNull
- in和notIn
- inSql和notInSql
- geSql,gtSql,leSql等
- group by
- orderByAsc和orderByDesc
- orderBy
- or和and
- last
- exists和noExists
- 分页
- 自定义代码生成器
重启mysql服务(cmd)
- 删除当前mysql服务:mysqld --remove 服务名称
- 查看是否存在data文件夹,有就将里面的文件都删除,没有就新建一个。
- 注册mysql 服务mysqld -install
- 初始化mysql:mysqld --initialize
- 初始化过程中会把登录密码初始化,可以在data文件中找到以.err结尾的文件
- 启动mysql服务:net start 服务名
- 登录mysql:mysql -uroot -p密码
- 修改密码:ALTER USER “root”@“localhost” IDENTIFIED BY “你的新密码”;
- hibernate:全自动的ORM框架,实现java object —表的映射。可以通过Java对象的方法,操作表中的数据,开发人员可以不了解或少了解sql语言。可以使用hibernate访问不同的数据库,不需要改变代码,通用不同的数据库。
- jpa规范,定义了访问数据库的各种操作,定义了一致的方法操作数据库,jpa有各种是心啊,hibernate,open-jpa,link
- mybatis:需要编写xml配置文件,在xml文件中编写sql语句,访问数据库,任何的操作需要使用xml文件。
- mybatis-plus:俗称mp,给mybatis又包装了一层,不再使用xml文件配置。
创建一个springboot工程,选择mysql模板服务,注意创建完毕后,会出现一个properties文件
# 应用名称 spring.application.name=mp # 数据库驱动: spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # 数据源名称 spring.datasource.name=defaultDataSource # 数据库连接地址 spring.datasource.url=jdbc:mysql://localhost:3306/blue?serverTimezone=UTC # 数据库用户名&密码: spring.datasource.username=*** spring.datasource.password=***
该文件用来配置和数据库连接的信息。
但为了方便,可以将其删除,创建一个名字一样,但是后缀是yml的文件,然后配置连接信息
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/hyb?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
username: root
password: 你的密码
pom.xml文件主要配置
org.springframework.boot spring-boot-starter mysql mysql-connector-java runtime 8.0.25 com.baomidou mybatis-plus-boot-starter 3.4.3.4 org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine
字和属性遵循驼峰命名规则,如数据库t_user类的名字就得是tUser。
package com.hyb.bean;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
public class tUser {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
private Integer age;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + ''' +
", age=" + age +
", email='" + email + ''' +
'}';
}
}
编写Mapper接口实现BaseMapper
package com.hyb.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.hyb.bean.tUser; public interface UserMapper extends BaseMapper{ }
给启动类编写扫描注解
package com.hyb.mp;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(value = "com.hyb.mapper")
public class MpApplication {
public static void main(String[] args) {
SpringApplication.run(MpApplication.class, args);
}
LAPTOP-MEE4I0AA46894
}
编写测试类
package com.hyb.mp;
import com.hyb.bean.tUser;
import com.hyb.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SuppressWarnings("all")
@SpringBootTest
class MpApplicationTests {
@Autowired
UserMapper userMapper;
@Test
public void test1(){
tUser user = new tUser();
user.setAge(20);
user.setEmail("468949484@qq.com");
user.setName("hyb");
int insert = userMapper.insert(user);
System.out.println(insert);
}
}
启动测试,可能出错有
Public Key Retrieval is not allowed
表示密码错误
Access denied for user ‘***’@‘localhost’ (using password: YES)
上面的情况一般有很多种错误
1)低版本的springboot才写data-username和data-password,springboot2后都写成username和password
2)password中如果是纯数字,比如00000会别识别成数字,要将用双引号括起来,变成字符串”00000“
3)注意是否存在两个配置文件,如propertites和yml文件,查看文件内是否有重复内容。
4)连接的driver和url可能有版本问题和时区问题
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver //8.0以上要加cj
url: jdbc:mysql://localhost:3306/hyb?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false //serverTimezone=UTC避免时区的问题
username: root
password: 你的密码 //密码不能错误,一般先自己在软件连接一下试试
5)授权问题,上网查阅。(如果软件能连接上而idea却连接不上,说明不是授权的问题)
6)接口占用问题,可能windows装上另一个版本的mysql,虽然这个版本的mysql没有连接,但是却开启了服务,将这个版本的服务关掉。其次,有可能是虚拟系统,例如你linux系统下mysql服务启动了。因为mysql公用一个端口3306,不能出现占用的情况。
日志输出在yml文件夹里配置日志,执行方法的可输出日志,查看sql语句的信息
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
CRUD
插入
- 前面的初始demo已经演示过,这里不在展示,需要知道的一个特性是,insert插入后,会将原来的对象改变,例如:上面我们通过user对象作为参数传入insert方法里,执行后,这个user对象的id便可以获取到,页就是数据库自动生成的id。
@Test
public void Test2(){
tUser hyb1 = new tUser(1, "hyb1", null, null);
int i = userMapper.updateById(hyb1);
System.out.println(i);
}
删除
按主键删除
@Test
public void Test3(){
int i = userMapper.deleteById(new tUser(2, null, null, null));
System.out.println(i);
}
按条件删除
@Test
public void test4(){
// 按照map删除,key为字段,value为该字段的某个值
Map map=new HashMap<>();
map.put("name","hyb1");
map.put("age",20);
int i = userMapper.deleteByMap(map);
System.out.println(i);//删除为0
}
批量删除
@Test
public void test5(){
// List ids=new ArrayList<>();
// ids.add(3);
// ids.add(4);
// ids.add(5);
List ids= Stream.of(4,5,6).collect(Collectors.toList());
int i = userMapper.deleteBatchIds(ids);
System.out.println(i);
}
查询
按照主键查询
@Test
public void test6(){
tUser user = userMapper.selectById(8);
if (user!=null){
System.out.println(user.toString());
}
}
按照条件查询
Mapmap=new HashMap<>(); map.put("name","hyb"); List tUsers = userMapper.selectByMap(map);//查询全部传入null for (tUser list:tUsers) { System.out.println(list); }
批量查询
ListActiveRecord(AR)tUsers = userMapper.selectBatchIds(Stream.of(7, 8).collect(Collectors.toList())); for (tUser t : tUsers) { System.out.println(t); }
mp提供了Model类,只要我们实现这个Model类就能实现数据库表对类的映射。
第一步,编写与数据库表对应的实体类
package com.hyb.bean; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.extension.activerecord.Model; public class Employee extends Model{ @TableId(value = "id",type = IdType.AUTO) private Integer id; private String name; private Integer age; public Employee() { } public Employee(Integer id, String name, Integer age) { this.id = id; this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Employee{" + "id=" + id + ", name='" + name + ''' + ", age=" + age + '}'; } }
package com.hyb.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.hyb.bean.Employee; public interface EmployeeMapper extends BaseMapper{ }
注意,该Mapper文件还是需要的,但是不用配置任何内容。
下面的例子,集成简单的CURD操作
package com.hyb.mp;
import com.hyb.bean.Employee;
import com.hyb.mapper.EmployeeMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
@SuppressWarnings("all")
public class ARTest {
// @Autowired
// EmployeeMapper employeeMapper;
// 实现Model类的好处是,我们连Mapper都不用自己注入了
@Test
public void test1(){
Employee hyb = new Employee(null, "hyb", 20);
hyb.insert();
}
@Test
public void Test2(){
Employee hyb1 = new Employee(1, "hyb1", 20);
hyb1.updateById();
}
@Test
public void test3(){
Employee employee = new Employee();
boolean b = employee.deleteById(9);
// 若使用不带参的删除方法删除需要给对象的id赋值
System.out.println(b);
}
@Test
public void test4(){
Employee employee = new Employee();
Employee employee1 = employee.selectById(1);
// List employees =
// employee.selectList(null);
// System.out.println(employees.size());//传入null查询全部
if (employee1!=null) {
System.out.println(employee1.toString());
}
}
}
idType
-
前面在初始化demo中,给id上了一个注解,这个注解里就有代表id类型的type属性,而type属性的值页关系到idType来解释。
-
该idType除了auto自动增长外,还有多个其他类型的值。
- none,为空,表示非主键,这个一般都用得较少。
- auto,自动增长。
- input,手动输入
- id_worker,实体类用Long int,表中用bigint
- uuid,页代表唯一值,但是比较混乱,id_worker要比这号。
- id_worker_str,实体类用String ,表中用varchar。
- 注意:id_worker是根据雪花算法来计算出的一种比uuid更加有序的唯一id。
- 但从自3.3.0开始,默认使用雪花算法+UUID(不含中划线),所以mp在新版本中使用ASSIGN_ID代替这三个随机id生成。
用户产生删除要求,表明的确删除了,但是实际上并没有删除。在数据库中只是标识该行是否删除的字段值改变了。
给指定的列添加逻辑删除的注解
@TableLogic private Integer delId;
在yml文件进行全局config配置
global-config: #与之前的configuration同级
db-config:
logic-delete-value: 0 #要删除的值
logic-not-delete-value: 1 #不进行删除的值
# logic-delete-field:
测试
@Test
public void t1(){
delMapper.deleteById(2);
// UPDATE del_test SET deld=0 WHERe id=? AND deld=1
// Del del = delMapper.selectById(1l);
SELECT id,name,deld AS delId FROM del_test WHERe id=? AND deld=0 查询自动拼接上deld
// System.out.println(del.toString());
}
自定义唯一id生成器
package com.hyb.bean;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.ImadcnIdentifierGenerator;
import java.util.Date;
public class CustomIdGenerator implements IdentifierGenerator {
@Override
public Number nextId(Object entity) {
DefaultIdentifierGenerator dn = new DefaultIdentifierGenerator();
// 以上是默认的雪花算法,在高并发下会有重复
// ImadcnIdentifierGenerator dn
// = new ImadcnIdentifierGenerator(nextUUID(entity));
// 而新的雪花算法则不会重复
long time = new Date().getTime();
System.out.println(time);
Long anx = dn.nextId(entity);
System.out.println(anx);
System.out.println(anx.toString()+time+"");
return time+anx;
}
}
自定义表名
在mp中,在类的上面用注解TableName来指定数据库表的名称,这样这个类就会自动映射到该表中,类名不用跟表名相等。
@TableName(value = "数据库表的名字")自定义列名
在mp中,只要在类的属性上加上TableFiled注解便可以自定义表名
@TableField(value = "对应表的列名")
但在开发中尽量使用驼峰命名规则,这样在类中就不用每次都指定列名了。例如:数据表的属性为t_name 在类中对应的属性是tName。
在resource目录下,我们可以自定义xml文件,然后写上sql语句。
之后,在yml文件中,配置mp的哪里写上另一个属性。
mybatis-plus:
mapper-locations: classpath*:
@Test
public void test1(){
QueryWrapper wrapper=new QueryWrapper<>();
Map map=new HashMap<>();
map.put("name","hyb1");
map.put("age","20");
wrapper.allEq(map);//传入空值代表查询全部
List employees = employeeMapper.selectList(wrapper);
employees.forEach(stu-> System.out.println(stu));
}
但在allEq里还有一个重写的方法allEq(Map
如果不指定第二个参数,当Map里存在null值的时候,默认是true,表示不忽略该空值条件,如果指定第二个参数为false,表示忽略Map里为空值的条件。
eq
@Test
public void test2(){
QueryWrapper e = new QueryWrapper<>();
e.eq("name","zyl");
List employees = employeeMapper.selectList(e);
employees.forEach(stu-> System.out.println(stu));
}
ne
- 和eq使用方法基本一样,表示不等于。
- 表示某个key的值大于某个值的条件
- 表示某个key的值大于等于某个值的条件
- 表示某个key的值小于某个值的条件
- 表示某个key的值小于等于某个值的条件。
- between(column,v1,v2)表示大于等于v1小于等于v2的条件
- notBetween(c,v1,v2)表示不在v1和v2范围的条件。
- like(c,v) 在sql语句中,该方法会在v的值前后都加上%,表示模糊查询
- 和like条件相反。用法一致。
- 和like条件一致,但leftLike会在值的前面加上%,likeRight会在值的后面加上%
- (column) 参数传入列名,表示该列是否为空
- 参数先传入一个列名,然后传入一个或多个的条件,表示该列的值在或不在这些值之中。
- 先传入一个列名,然后传入一条sql语句。该方法用来嵌套查询。例如:inSql(‘age’,"select age from m where id=1)"代表的sql语句是select * from t where age in (select age form m where id=1)
- 从上面的封装的方法中可以看出规律,这些方法表示封装sql子句,然后条件的谓语是in > < >=等。比如,gtSql(‘age’,"select age from m where id=1)"代表的sql语句是select * from t where age > (select age form m where id=1);
该方法使用有些特殊,需要配合select方法使用
@Test
public void t3(){
QueryWrapper e = new QueryWrapper<>();
e.select("name,count(*) count");
e.groupBy("name");//如果传入多个分组条件,需要传入一个集合
List tUsers = userMapper.selectList(e);
tUsers.forEach(tUser -> System.out.println(tUser));
}
orderByAsc和orderByDesc
- 直接使用,不用配合select方法使用,传入一个列名和多个列名,或列名的集合便可以。
方法是升序和降序排序的结合
Children orderBy(boolean condition, boolean isAsc, R column); Children orderBy(boolean condition, boolean isAsc, Listcolumns);
传入布尔条件,一般为true,isAsc代表是否升序排序,后者为一列或者多列的集合。
用来连接多个条件
@Test
public void t4(){
QueryWrapper e = new QueryWrapper<>();
// e.eq("name","hyb")
// .or().eq("age",20);
e.eq("name","hyb")
.and(new Consumer>() {
@Override
public void accept(QueryWrapper tUserQueryWrapper) {
tUserQueryWrapper.eq("age",20);
}
});
List tUsers = userMapper.selectList(e);
tUsers.forEach(tUser -> System.out.println(tUsers));
}
last
- 该方法可以在原有的sql语句后添加sql语句。直接用链式的方法在各个条件拼接的方法后调用就行了。一般用来拼接分页查询,如果在sql语句后拼接limit 谓语,就可以限定输出结果的数量。
- 用来拼接sql语句谓语exists操作,后者跟sql子句查询。
配置带有@Configuration注解的类。
//加上这个注解相当于配置文件
@Configuration
public class Config {
// 最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
System.out.println("---------------------------------"
+"拦截器执行了"+"--------------------------------------"
);
return interceptor;
}
}
将此文件放在和Springboot启动文件同目录下。或者另放一个目录,但要在启动类上加上@Import({Config.class})的注解。
测试。
public void t1(){
QueryWrapper qw = new QueryWrapper<>();
Page t = new Page<>(1,2);
Page tUserIPage = userMapper.selectPage(t, qw);
// 获取记录
List records =
tUserIPage.getRecords();
records.forEach(tUser -> System.out.println(tUser));
}
获得的tUserIpage包含了多种方法,这些方法可以获取返回的分页信息。如:总页数,总记录数,当前页记录等。
package com.hyb.mp;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class AutoMP {
public static void main(String[] args) {
FastAutoGenerator.create("jdbc:mysql://localhost/hyb?useUnicode=true&characterEncoding=utf8", "root", "15717747056HYb!")
// 全局配置
.globalConfig(builder -> {
builder.author("hyb") // 设置作者
// .enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir(System.getProperty("user.dir") + "/src/main/java"); // 指定输出目录
// .commentDate("yyyy-MM-dd"); //调整时间格式
})
// 包配置
.packageConfig(builder -> {
builder.parent("com.hyb") // 设置父包名
.moduleName("Auto") // 设置父包模块名
// .entity("entity")
// .service("service")
// .serviceImpl("serviceImpl")
// .controller("controller")
// .mapper("mapper")
// .xml("mapper")
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir")+"/src/main/resources/mapper")); // 设置mapperXml生成路径
})
// 策略配置
.strategyConfig(builder -> {
builder.addInclude(getTables("all")) // 设置需要生成的表名,多个用英文隔开
// .addTablePrefix("t_", "c_") // 设置过滤表前缀
.serviceBuilder() // service 配置策略
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImpl")
.entityBuilder()
.idType(IdType.AUTO)//设置主键类型
.columnNaming(NamingStrategy.underline_to_camel)//驼峰命名规则
.enableActiveRecord() //开启AR模式
// .enableLombok() // 开启Lombok
// .logicDeleteColumnName("deleted") // 说明逻辑删除(软删除)是哪个字段
.enableTableFieldAnnotation() // 属性上加说明注解
.controllerBuilder() // controller 策略配置
.formatFileName("%sController")
.enableRestStyle() // 开启 RestController
.enableHyphenStyle() //驼峰连字符
.mapperBuilder() //mapper 策略配置
.superClass(BaseMapper.class) // 继承哪个父类
.formatMapperFileName("%sMapper")
// .enableMapperAnnotation() // @mapper 开启
.formatXmlFileName("$sMapper"); // xml 名
}).execute();
}
protected static List getTables(String tables) {
return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}
}



