智慧团建网站链接,怎样做免费的网站,四川网站建设平台,旅游网站建设方案两百字常用注解
TableName
MyBatis-Plus在确定操作的表时#xff0c;由BaseMapper的泛型决定即实体类型决定#xff0c;且默认操作的表名和实体类型的类名一致,如果不一致则会因找不到表报异常
//向表中插入一条数据
Test
public void testInsert(){User user new User(null, TableName
MyBatis-Plus在确定操作的表时由BaseMapper的泛型决定即实体类型决定且默认操作的表名和实体类型的类名一致,如果不一致则会因找不到表报异常
//向表中插入一条数据
Test
public void testInsert(){User user new User(null, 张三, 23, zhangsanatguigu.com);//INSERT INTO user (id, name, age, email) VALUES ( ?, ?, ?, ? )int result userMapper.insert(user);System.out.println(受影响行数result);//获取插入数据的主键id为1475754982694199298//MyBatis-Plus在实现插入数据时如果我们没有指定id,他默认基于雪花算法的策略生成一个id插入到表中System.out.println(id自动获取user.getId());
}在实体类类型上添加TableName(“t_user”)用来标识实体类对应的表
Data
TableName(t_user)
public class User{private Long id;private String name;private Integer age;private String email;public User() {}
}全局配置: 实际开发中实体类所对应的表都有固定的前缀(例如t_ 或tbl_),可以使用MyBatis-Plus提供的全局配置, 为所有实体类所对应的表名设置默认的前缀
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl# 设置MyBatis-Plus的全局配置global-config:db-config:# 设置实体类所对应的表的统一前缀table-prefix: t_TableId的value属性和type属性
MyBatis-Plus在实现CRUD时, 会默认将实体类的id属性作为主键列, 并在插入数据时默认基于雪花算法的策略生成一个id擦入到数据库
测试将实体类中的属性id改为uid(此时uid对于MyBatis-Plus来说就是一个普通字段)将表中的字段id也改为uid
//向表中插入一条数据
Test
public void testInsert(){User user new User(null, 张三, 23, zhangsanatguigu.com);//INSERT INTO user (name, age, email) VALUES ( ?, ?, ?)//uid对于MyBatis-Plus来说就是一个普通字段,如果我们没有指定值默认就向数据表插入的就为null,不再是基于雪花算法生成的值int result userMapper.insert(user);System.out.println(受影响行数result);System.out.println(id自动获取user.getId());
}在实体类的属性上添加TableId指定value属性表示将该属性对应的字段作为主键列(默认以属性的属性名对应的字段名为主键字段)
TableId的value属性: 用来指定该属性对应的字段名作为主键
Data
public class User {//TableId(valueuid)TableId(uid)private Long id;private String name;private Integer age;private String email;
}//向表中插入一条数据
Test
public void testInsert(){User user new User(null, 张三, 23, zhangsanatguigu.com);//INSERT INTO user (uid,name, age, email) VALUES ( ?, ?, ?,?)int result userMapper.insert(user);System.out.println(受影响行数result);System.out.println(id自动获取user.getId());
}TableId的type属性用来定义主键的生成策略, IdType表示主键类型
如果设置了主键的值,就会根据设置的值插入数据库, 不再基于任何主键策略
值描述IdType.ASSIGN_ID默认)基于雪花算法的策略生成数据id与数据库id是否设置自增无关IdType.AUTO使用数据库的自增策略注意该类型请确保数据库设置了id自增
在实体类的属性上添加TableId指定type属性设置主键的生成策略
Data
public class User {TableId(valueuid,type IdType.AUTO)TableId(uid)private Long id;private String name;private Integer age;private String email;
}
//向表中插入一条数据
Test
public void testInsert(){User user new User(null, 张三, 23, zhangsanatguigu.com);//INSERT INTO user (name, age, email) VALUES ( ?, ?, ?,?)//采用主键自动递增策略后id就不用再通过雪花算法生成一个值赋给id属性然后插入数据库中,主键自动递增默认就会自动递增不用赋值int result userMapper.insert(user);System.out.println(受影响行数result);System.out.println(id自动获取user.getId());
}全局配置: 可以使用MyBatis-Plus提供的全局配置, 设置统一的主键生成策略
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl# 设置MyBatis-Plus的全局配置global-config:db-config:# 设置实体类所对应的表的统一前缀table-prefix: t_# 设置统一的主键生成策略id-type: auto雪花算法
随着数据规模的增长雪花算法的作用就是应对逐渐增长的访问压力和数据量
数据库性能的扩展方式主要包括业务分库、主从复制(主服务器实现写的功能,从服务器实现写的功能, 保存证主从服务器的数据一致性)数据库分表
数据库分表是将不同业务数据分散存储到不同的数据库服务器能够支撑百万甚至千万用户规模的业务
如果业务继续发展同一业务的单表数据也会达到单台数据库服务器的处理瓶颈, 此时就需要对单表数据进行拆分
单表数据拆分有两种方式垂直分表和水平分表 垂直分表适合将表中某些不常用且占了大量空间的列拆分出去,用户在筛选其他用户的时候主要是用 age 和 sex 两个字段进行查询而 nickname 和 description 两个字段本身比较长主要用于展示一般不会在业务查询中用到。因此我们可以将这两个字段独立到另外一张表中这样在查询 age 和 sex 时就能带来一定的性能提升 水平分表适合表行数特别大的表根据表的访问性能 , 简单的表行数超过 5000 万就必须进行分表, 比较复杂的表, 可能超过 1000 万就要分表了 , 水平分表相比垂直分表会引入更多的复杂性例如要求全局唯一的数据id该如何处理 水平分表相比垂直分表会引入更多的复杂性例如要求全局唯一的数据id该如何处理 主键递增: 可以按照 1000000 的范围大小进行分段1 ~ 999999 放到表 1中1000000 ~ 1999999 放到表 2 中
复杂点分段大小的选取不好确定分段太小会导致切分后子表数量过多增加维护复杂度分段太大可能会导致单表依然存在性能问题一般建议分段大小在 100 万至 2000 万之间具体需要根据业务选取合适的分段大小优点可以随着数据的增加平滑地扩充新的表。例如现在的用户是 100 万如果增加到 1000 万只需要增加新的表就可以了原有的数据不需要动缺点分布不均匀, 假如按照 1000 万来进行分表有可能某个分段实际存储的数据量只有 1 条而另外一个分段实际存储的数据量有 1000 万条
取模: 如果有10 个数据库表可以用 user_id % 10 的值来表示数据所属的数据库表编号ID 为 985 的用户放到编号为 5 的子表中
复杂点初始表数量的大小不好确定: 表数量太多维护比较麻烦表数量太少又可能导致单表性能存在问题优点表分布比较均匀缺点扩充新的表很麻烦所有数据都要重分布
雪花算法是由Twitter公布的分布式主键生成算法它能够保证不同表的主键的不重复性以及相同表的主键的有序性
优点整体上按照时间自增排序并且整个分布式系统内不会产生ID碰撞并且效率较高 TableField
在实体类属性上使用TableField, 表示当前属性对应的字段为一个普通字段(默认属性名就是表中的字段名)
TableField的value属性可以设置属性所对应的字段名若实体类中的属性使用的是驼峰命名风格而表中的字段使用的是下划线命名风格, 此时MyBatis-Plus会自动将下划线命名风格转化为驼峰命名风格
Data
public class User {private Long id;//userName对应的SQL语句INSERT INTO user (id, user_name, age, email ) VALUES ( ?, ?, ?, ? )//name对应的SQL语句INSERT INTO user (id, name, age, email ) VALUES ( ?, ?, ?, ? )TableField(user_name)private String userName;private Integer age;private String email;
}
//向表中插入一条数据
Test
public void testInsert(){User user new User(null, 张三, 23, zhangsanatguigu.com);//int result userMapper.insert(user);System.out.println(受影响行数result);System.out.println(id自动获取user.getId());
}TableLogic
数据库表中的删除分为两种
物理删除真实删除将对应数据从数据库中删除之后查询不到此条被删除的数据逻辑删除假删除将对应数据中代表是否被删除字段的状态修改为“被删除状态”之后在数据库中仍旧能看到此条数据记录(可以进行数据恢复)
第一步: 数据库中创建逻辑删除状态列设置默认值为0(表示该记录处于未删除状态,1表示已删除状态) 第二步: 实体类中添加逻辑删除属性
Data
public class User {TableId(uid)private Long id;TableFiled(user_name)private String name;private Integer age;private String email;TableLogicprivate Integer isDeleted;
}测试逻辑删除
//通过多个id批量删除
Test
public void testDeleteBatchIds(){ListLong idList Arrays.asList(1L, 2L, 3L);//物理删除执行的SQL: DELETE FROM user WHERE uid IN ( ? , ? , ? )//逻辑删除真正执行的是修改: UPDATE t_user SET is_deleted1 WHERE uid? AND is_deleted0int result userMapper.deleteBatchIds(idList);System.out.println(受影响行数result);
}//查询所有数据,返回一个list集合
Test
public void testSelectList(){//直接查询:SELECT uid As id,user_name As name,age,email FROM user//查询数据被逻辑删除的数据默认不会被查询:SELECT uid As id,user_name As name,age,email ,is_deleted FROM t_user WHERE is_deleted0ListUser list userMapper.selectList(null);list.forEach(System.out::println);
}条件构造器和常用接口
wapper介绍 条件构造器的两个条件之间默认就是AND并列关系,如果需要或者的关系则需要调用构造器的or()方法
条件构造器类型作用Wrapper条件构造抽象类最顶端父类AbstractWrapper用于查询条件封装生成 sql 的 where 条件QueryWrapper查询/删除条件封装UpdateWrapperUpdate条件封装AbstractLambdaWrapper使用Lambda语法LambdaQueryWrapper用于Lambda语法使用的查询WrapperLambdaUpdateWrapperLambda更新封装Wrapper
Data
public class User {private Long id;TableFiled(user_name)private String name;private Integer age;private String email;TableLogicprivate Integer isDeleted;
}QueryWrapper
使用queryWrapper实现查询功能
springBootTest
public class MybatisPlusWrapperTest{Autowiredprivate UserMapper userMapper;//组装查询条件Testpublic void test01(){//查询用户名包含a年龄在20到30之间并且邮箱不为null的用户信息,使用了逻辑删除查询的都是未删除的数据/*SELECT id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted0 AND (username LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL)*/QueryWrapperUser queryWrapper new QueryWrapper();//链式结构的调用,这些方法的返回值最后都是queryWrapper对象queryWrapper.like(username, a).between(age, 20, 30).isNotNull(email);//将查询的结果集映射到实体类的属性然乎放入到List集合当中ListUser list userMapper.selectList(queryWrapper);list.forEach(System.out::println);}//组装排序条件Testpublic void test02(){//按年龄降序查询用户如果年龄相同则按id升序排列//SELECT id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted0 ORDER BY age DESC,id ASCQueryWrapperUser queryWrapper new QueryWrapper();queryWrapper.orderByDesc(age).orderByAsc(id);ListUser users userMapper.selectList(queryWrapper);users.forEach(System.out::println);}
}查询特定的字段和组装子查询
springBootTest
public class MybatisPlusWrapperTest{Autowiredprivate UserMapper userMapper;//查询用户信息的user_name和age字段,selectList默认是查询所有的字段Testpublic void test05() {//SELECT user_name,age FROM t_user WHERE is_deleted0QueryWrapperUser queryWrapper new QueryWrapper();queryWrapper.select(user_name, age);//selectMaps()查询结果是一个Map集合 被放入到了List集合通常配合select()使用避免User对象中没有被查询到的列值为nullListMapString, Object maps userMapper.selectMaps(queryWrapper);maps.forEach(System.out::println);}//组装子查询,查询id小于等于3的用户信息Testpublic void test06() {//SELECT id,use_rname,age,email,is_deleted FROM t_user WHERE is_deleted0 AND id IN(select id from t_user where id 3)QueryWrapperUser queryWrapper new QueryWrapper();//第一个参数是子查询要判断的字段,第二个参数是子查询要判断的数据queryWrapper.inSql(id, select id from t_user where id 3);ListUser list userMapper.selectList(queryWrapper);list.forEach(System.out::println);}
}条件构造器的优先级默认按照从左到右的顺序执行, 调用构造器的and()方法相当于在sql语句加了一个括号,使用queryWrapper实现修改和删除功能
springBootTest
public class MybatisPlusWrapperTest{Autowiredprivate UserMapper userMapper;//组装逻辑删除条件Testpublic void test03(){//将年龄大于20并且用户名中包含有a或邮箱为null的用户信息修改,条件构造器默认就是并列条件Testpublic void test04() {QueryWrapperUser queryWrapper new QueryWrapper();//UPDATE t_user SET age ?, email ? WHERE is_deleted0 AND (user_name LIKE ? AND age ? OR email IS NULL)queryWrapper.like(user_name, a).gt(age, 20).or().isNull(email);//设置实体类中要修改的字段,没设置的字段不会被修改User user new User();user.setAge(18);user.setEmail(useratguigu.com);int result userMapper.update(user, queryWrapper);System.out.println(受影响的行数 result);}//构造器的优先级,将用户名中包含有a并且年龄大于20或邮箱为null的用户信息修改Testpublic void test04() {QueryWrapperUser queryWrapper new QueryWrapper();//UPDATE t_user SET age?, email? WHERE is_deleted0 AND (user_name LIKE ? AND (age ? OR email IS NULL))//queryWrapper.like(user_name, a).and((QueryWrapper i){return i.gt(age, 20).or().isNull(email)});//lambda表达式内的逻辑优先运算,i表示条件构造器,and方法的参数是ConsumerQueryWrapper实体类接口的实现类//queryWrapper.like(user_name, a).and((QueryWrapper i){return i.gt(age, 20).or().isNull(email)});queryWrapper.like(user_name, a).and(i - i.gt(age, 20).or().isNull(email));User user new User();user.setAge(20);user.setEmail(useratguigu.com);int result userMapper.update(user, queryWrapper);System.out.println(受影响的行数 result);}//逻辑删除只能删除未删除状态的数据即is_deleted0, 删除email为空的用户//UPDATE t_user SET is_deleted1 WHERE is_deleted0 AND (email IS NULL)QueryWrapperUser queryWrapper new QueryWrapper();queryWrapper.isNull(email);//条件构造器也可以构建删除语句的条件int result userMapper.delete(queryWrapper);System.out.println(受影响的行数 result);}
}UpdateWrapper
使用UpdateWrapper实现修改功能,不仅可以设置修改的条件还可以设置要修改的字段(不用再创建实体类对象),修改的字段和条件可以分开写也可以连这写
springBootTest
public class MybatisPlusWrapperTest{Autowiredprivate UserMapper userMapper;Testpublic void test07() {//将年龄大于20或邮箱为null并且用户名中包含有a的用户信息修改UpdateWrapperUser updateWrapper new UpdateWrapper();//设置修改的字段(以下两个updateWrapper可以连着写)updateWrapper.set(age, 18).set(email, useratguigu.com);//设置修改的条件, lambda表达式内的逻辑优先运算updateWrapper.like(user_name, a).and(i - i.gt(age, 20).or().isNull(email));//UPDATE t_user SET age?,email? WHERE is_deleted0 AND (user_name LIKE ? AND(age ? OR email IS NULL))//由于之前设置了修改的字段,所以此时不再需要实体类,传递的参数为nullint result userMapper.update(null, updateWrapper);System.out.println(result);}
}condition组装条件
在真正开发的过程中组装条件是常见的功能而这些条件数据来源于用户输入因此我们在组装这些条件时必须先判断用户是否选择了这些条件若选择则需要组装该条件若没有选择则一定不能组装以免影响SQL执行的结果
springBootTest
public class MybatisPlusWrapperTest{Autowiredprivate UserMapper userMapper;//调用条件构造器方法时不使用boolean类型的condition条件Testpublic void test08() {//定义查询条件有可能为null用户未输入或未选择String username null;Integer ageBegin 10;Integer ageEnd 24;QueryWrapperUser queryWrapper new QueryWrapper();//StringUtils是由Mybatis-pius提供的工具类,isNotBlank()判断某字符串是否不为空且长度不为0且不由空白符(whitespace)构成if(StringUtils.isNotBlank(username)){queryWrapper.like(user_name,username);}if(ageBegin ! null){queryWrapper.ge(age, ageBegin);}if(ageEnd ! null){queryWrapper.le(age, ageEnd);}//由于username为null所以只有年龄作为条件//SELECT id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted0 AND (age ? AND age ?)ListUser users userMapper.selectList(queryWrapper);users.forEach(System.out::println);}//调用条件构造器方法时使用boolean类型的condition条件Testpublic void test08UseCondition() {//定义查询条件有可能为null用户未输入或未选择String username null;Integer ageBegin 10;Integer ageEnd 24;QueryWrapperUser queryWrapper new QueryWrapper();//方法的参数传入一个boolean类型的condition条件,如果条件为true则组装后面的条件queryWrapper.like(StringUtils.isNotBlank(username), username, username).ge(ageBegin ! null, age, ageBegin) .le(ageEnd ! null, age, ageEnd);//SELECT id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted0 AND (age ? AND age ?)ListUser users userMapper.selectList(queryWrapper);users.forEach(System.out::println);}
}LambdaQueryWrapper/UpdateWrapper
Data
public class User {private Long id;TableFiled(user_name)private String name;private Integer age;private String email;TableLogicprivate Integer isDeleted;
}当使用字符串描述一个字段时容易写错出现运行时错误,使用一个函数式接口SFunction(实体类,?)访问实体类某个属性,底层自动获取该属性对应字段作为条件
springBootTest
public class MybatisPlusWrapperTest{Autowiredprivate UserMapper userMapper;//使用LambdaQueryWrapper查询Testpublic void test09() {//定义查询条件有可能为null用户未输入String username a;Integer ageBegin 10;Integer ageEnd 24;LambdaQueryWrapperUser queryWrapper new LambdaQueryWrapper();queryWrapper.like(StringUtils.isNotBlank(username), User::getName, username).ge(ageBegin ! null, User::getAge, ageBegin).le(ageEnd ! null, User::getAge, ageEnd);//SELECT id,user_name AS name,age,email,is_deleted FROM t_user WHERE (user_name LIKE ? age ? AND age ?)ListUser users userMapper.selectList(queryWrapper);users.forEach(System.out::println);}//使用LambdaUpdateWrapperTestpublic void test10() {//组装set子句设置修改的条件和字段LambdaUpdateWrapperUser updateWrapper new LambdaUpdateWrapper();updateWrapper.set(User::getAge, 18).set(User::getEmail, useratguigu.com).like(User::getName, a).and(i - i.lt(User::getAge, 24).or().isNull(User::getEmail)); User user new User();//UPDATE t_user SET age?,email? WHERE is_deleted0 AND (user_name LIKE ? AND(age ? OR email IS NULL))int result userMapper.update(user, updateWrapper);System.out.println(受影响的行数 result);}
}插件
查
MyBatis Plus自带分页插件只要简单的配置即可实现分页功能
分页的本质是我们先写了查询功能,MyBatis Plus对我们的查询操作进行拦截然后增加一些额外的操作达到分页的功能
Configuration
MapperScan(com.atguigu.mybatisplus.mapper) //可以将主类中的扫描接口的注解移到此处
public class MybatisPlusConfig {Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {// 配置MyBatis Plus中插件的对象MybatisPlusInterceptor interceptor new MybatisPlusInterceptor();// 在插件对象中添加内部插件(拦截器)并设置数据库类型interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}
}springBootTest
public class MybatisPlusPluginsTest{Autowiredprivate UserMapper userMapper;Testpublic void testPage(){//在分页对象中设置分页参数,当前页码数和每页显示的记录数PageUser page new Page(1, 5);//方法的参数是继承了IPage的类型Page和查询的条件构造器queryWrapper,将查询结果都封装到了分页对象当中//SELECT id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted0 LIMIT ? ?userMapper.selectPage(page, null);//获取分页数据ListUser list page.getRecords();//获取分页相关的数据设置分页相关的超链接和按钮list.forEach(System.out::println);System.out.println(当前页page.getCurrent());System.out.println(每页显示的条数page.getSize());System.out.println(总记录数(未删除状态的数据)page.getTotal());System.out.println(总页数page.getPages());System.out.println(是否有上一页page.hasPrevious());System.out.println(是否有下一页page.hasNext());}
}自定义查询语句实现分页
自定义查询语句通过分页插件实现分页功能: 根据年龄查询用户列表分页显示
//UserMapper中自定义接口方法
Repository
public interface UserMapper extends BaseMapperUser {//page表示分页对象,xml中的占位符可以从里面进行取值,传递参数Page必须放在第一位表示开启自动分页功能PageUser selectPageVo(Param(page) PageUser page, Param(age) Integer age);
}spring:# 配置数据源信息datasource:# 配置数据源类型type: com.zaxxer.hikari.HikariDataSource# 配置连接数据库的各个信息driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mybatis_plus?characterEncodingutf-8userSSLfalseusername: rootpassword: 123456
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl# 设置MyBatis-Plus的全局配置global-config:db-config:# 设置实体类所对应的表的统一前缀table-prefix: t_# 设置统一的主键生成策略id-type: auto# 配置类型别名所对应的包,默认的别名是简类名且不区分大小写type-aliases-package: com.atguigu.mybatisplus.pojo# 扫描通用枚举的包type-enums-package: com.atguigu.mybatisplus.enums UserMapper.xml中编写SQL
!--SQL片段记录基础字段--
sql idBaseColumnsid,username,age,email/sql
!--IPageUser selectPageVo(PageUser page, Integer age);--
select idselectPageVo resultTypeUserSELECT include refidBaseColumns/include FROM t_user WHERE age {age}
/select?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.atguigu.mybatisplus.mapper.UserMapper!--IPageUser selectPageVo(PageUser page, Integer age);--select idselectPageVo resultTypeUserSELECT id,user_name,age,email FROM t_user WHERE age #{age}/select
/mapper
Test
public void testSelectPageVo(){//设置分页参数PageUser page new Page(1, 5);userMapper.selectPageVo(page, 20);//获取分页数据ListUser list page.getRecords();list.forEach(System.out::println);System.out.println(当前页page.getCurrent());System.out.println(每页显示的条数page.getSize());System.out.println(总记录数page.getTotal());System.out.println(总页数page.getPages());System.out.println(是否有上一页page.hasPrevious());System.out.println(是否有下一页page.hasNext());
}
乐观锁与悲观锁
模拟修改冲突
数据库中增加商品表并插入一条数据
CREATE TABLE t_product(
id BIGINT(20) NOT NULL COMMENT 主键ID,
NAME VARCHAR(30) NULL DEFAULT NULL COMMENT 商品名称,
price INT(11) DEFAULT 0 COMMENT 价格,
VERSION INT(11) DEFAULT 0 COMMENT 乐观锁版本号,
PRIMARY KEY (id));
--插入一条数据
INSERT INTO t_product (id, NAME, price) VALUES (1, 外星人笔记本, 100);
实体类和mapper接口
import lombok.Data;
Data
public class Product {private Long id;private String name;private Integer price;private Integer version;
}
Repository
public interface ProductMapper extends BaseMapperProduct {
}
Test
public void testConcurrentUpdate() {//小李取出的价格100Product p1 productMapper.selectById(1L);System.out.println(小李取出的价格 p1.getPrice());//小王取出的价格100Product p2 productMapper.selectById(1L);System.out.println(小王取出的价格 p2.getPrice());//小李将价格加了50元存入了数据库p1.setPrice(p1.getPrice() 50);int result1 productMapper.updateById(p1);System.out.println(小李修改结果 result1);//小王将商品减了30元存入了数据库p2.setPrice(p2.getPrice() - 30);int result2 productMapper.updateById(p2);System.out.println(小王修改结果 result2);//最后的价格70Product p3 productMapper.selectById(1L);System.out.println(最后的结果 p3.getPrice());
}
乐观锁实现流程
第一步: 数据库中添加version字段
第二步取出记录时同时获取当前记录的版本号
SELECT id,name,price,versionFROM product WHEREid 1;
第三步更新: version 1如果where语句中的version版本不对即在我更新之前这行记录的版本号已经发生了改变则更新失败
UPDATE product SET price price50, version version 1 WHERE id1 AND version1
Mybatis-Plus实现乐观锁
修改实体类添加Version注解表示乐观锁版本号字段
import com.baomidou.mybatisplus.annotation.Version;
import lombok.Data;
Data
public class Product {private Long id;private String name;private Integer price;Version//表示乐观锁版本号字段private Integer version;
}
添加乐观锁插件配置
Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor interceptor new MybatisPlusInterceptor();//添加分页插件interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//添加乐观锁插件interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return interceptor;
}
Test
public void testConcurrentUpdate() {//小李取出的价格100Product p1 productMapper.selectById(1L);System.out.println(小李取出的价格 p1.getPrice());//小王取出的价格100Product p2 productMapper.selectById(1L);System.out.println(小王取出的价格 p2.getPrice());//小李将价格加了50元存入了数据库p1.setPrice(p1.getPrice() 50);//update t_product set name ?,price ?,version ?(原版本号1) where id ? and version ?int result1 productMapper.updateById(p1);System.out.println(小李修改结果 result1);//小王将商品减了30元存入数据库时发现与取出数据的版本号不一致故更新失败p2.setPrice(p2.getPrice() - 30);//此时执行时版本号发生了改变,更新失败int result2 productMapper.updateById(p2);System.out.println(小王修改结果 result2);//最后的价格150Product p3 productMapper.selectById(1L);System.out.println(最后的结果 p3.getPrice());
}
优化修改流程
Test
public void testConcurrentVersionUpdate() {//小李取数据Product p1 productMapper.selectById(1L);//小王取数据Product p2 productMapper.selectById(1L);//小李修改 50p1.setPrice(p1.getPrice() 50);int result1 productMapper.updateById(p1);System.out.println(小李修改的结果 result1);//小王修改 - 30p2.setPrice(p2.getPrice() - 30);int result2 productMapper.updateById(p2);System.out.println(小王修改的结果 result2);if(result2 0){//失败重试重新获取version并更新p2 productMapper.selectById(1L);p2.setPrice(p2.getPrice() - 30);result2 productMapper.updateById(p2);}System.out.println(小王修改重试的结果 result2);//最后的价格120Product p3 productMapper.selectById(1L);System.out.println(老板看价格 p3.getPrice());
}
代码生成器
dependencygroupIdcom.baomidou/groupIdartifactIdmybatis-plus-generator/artifactIdversion3.5.1/version
/dependency
dependencygroupIdorg.freemarker/groupIdartifactIdfreemarker/artifactIdversion2.3.31/version
/dependency
public class FastAutoGeneratorTest {public static void main(String[] args) {FastAutoGenerator.create(jdbc:mysql://127.0.0.1:3306/mybatis_plus?characterEncodingutf-8userSSLfalse, root, 123456).globalConfig(builder - {builder.author(atguigu) // 设置作者//.enableSwagger() // 开启 swagger 模式.fileOverride() // 覆盖已生成文件.outputDir(D://mybatis_plus); // 指定输出目录}).packageConfig(builder - {builder.parent(com.atguigu) // 设置父包名.moduleName(mybatisplus) // 设置父包模块名.pathInfo(Collections.singletonMap(OutputFile.mapperXml, D://mybatis_plus));// 设置mapperXml生成路径}).strategyConfig(builder - {builder.addInclude(t_user) // 设置需要生成的表名.addTablePrefix(t_, c_); // 设置过滤表前缀}).templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板默认的是Velocity引擎模板.execute();}
}
多数据源
步骤
适用于多种场景纯粹多库(操作的表分布在不同数据库当中)、 读写分离(有的数据库负责读的功能,有的数据库负责写的功能)、 一主多从、 混合模式等
第一步: 创建mybatis_plus数据库和user表,mybatis_plus_1数据库和product表
--创建mybatis_plus数据库
CREATE DATABASE mybatis_plus /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
use mybatis_plus;
--创建user表
CREATE TABLE user (id bigint(20) NOT NULL COMMENT 主键ID,name varchar(30) DEFAULT NULL COMMENT 姓名,age int(11) DEFAULT NULL COMMENT 年龄,email varchar(50) DEFAULT NULL COMMENT 邮箱,PRIMARY KEY (id)
) ENGINEInnoDB DEFAULT CHARSETutf8;
--向user表中插入数据
INSERT INTO user (id, name, age, email) VALUES
(1, Jone, 18, test1baomidou.com),
(2, Jack, 20, test2baomidou.com),
(3, Tom, 28, test3baomidou.com),
(4, Sandy, 21, test4baomidou.com),
(5, Billie, 24, test5baomidou.com);
--创建mybatis_plus_1数据库
CREATE DATABASE mybatis_plus_1 /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
use mybatis_plus_1;
--创建product表
CREATE TABLE product(
id BIGINT(20) NOT NULL COMMENT 主键ID,
name VARCHAR(30) NULL DEFAULT NULL COMMENT 商品名称,
price INT(11) DEFAULT 0 COMMENT 价格,
version INT(11) DEFAULT 0 COMMENT 乐观锁版本号,
PRIMARY KEY (id)
);
--向product表插入数据
INSERT INTO product (id, NAME, price) VALUES (1, 外星人笔记本, 100);
第二步:引入依赖
dependencygroupIdcom.baomidou/groupIdartifactIddynamic-datasource-spring-boot-starter/artifactIdversion3.5.0/version
/dependency
第三步: 配置多数据源, 注释掉之前的数据库连接, 添加新配置
spring:# 配置数据源信息datasource:dynamic:# 设置默认的数据源或者数据源组,默认值即为masterprimary: master# 严格匹配数据源,默认false.true表示未匹配到指定数据源时抛异常,false表示未匹配到使用默认数据源strict: falsedatasource:master:url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncodingutf-8useSSLfalsedriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 123456slave_1:url: jdbc:mysql://localhost:3306/mybatis_plus_1?characterEncodingutf-8useSSLfalsedriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 123456
第四步: 创建实体类封装表中查询的数据
//封装产品信息的实体类
Data
public class Product {private Integer id;private String name;private Integer price;private Integer version;
}
//封装用户信息的实体类
Data
public class User {private Integer id;private String userName;private Integer age;private Integer sex;private String email;private Integer isDeleted;
}
第五步: 编写mapper接口
Repository
public interface ProductMapper extends BaseMapperProduct {
}
Repository
public interface UserMapper extends BaseMapperUser {
}
第六步: 创建商品和用户service和其实现类,使用 DS注解切换数据源
Ds可以注解在方法上或类上(类中所有的方法默认都有该注解)同时存在就近原则方法上注解优先于类上注解
注解结果没有DS注解操作的是默认的数据源DS(dsName”)dsName可以为组名也可以为具体某个库的名称
//用户service和其实现类
public interface UserService extends IServiceUser {}
DS(master) //指定所操作的数据源,user表在master数据源当中
Service
public class UserServiceImpl extends ServiceImplUserMapper, User implementsUserService {
}
//商品service和其实现类
public interface ProductService extends IServiceProduct {}
DS(slave_1)//product表在slave_1数据源当中
Service
public class ProductServiceImpl extends ServiceImplProductMapper, Product implements ProductService {
}
第七步: 编写Spring Boot主程序的启动类
SpringBootApplication
MapperScan(com.atguigu.mybatisplus.mapper)
public class MybatisPlusDatasourceApplication {public static void main(String[] args) {SpringApplication.run(MybatisPlusDatasourceApplication.class, args);}
}
第八步: 由于每个库都有一张表,如果通过一个测试可以分别获取到用户数据与商品数据成功说明多库模拟成功
如果我们实现读写分离将写操作方法加上主库数据源读操作方法加上从库数据源自动切换就能实现读写分离
SpringBootTest
public class MybatisPlusDatasourceApplicationTests {Autowiredprivate UserService userService;Autowiredprivate ProductService productService;Testpublic void testDynamicDataSource(){//都能顺利获取对象System.out.println(userService.getById(1));System.out.println(productService.getById(1));}
}
MyBatisX插件
在真正开发过程中对于一些复杂的SQL多表联查我们就需要自己去编写代码和SQL语句这个时候可以使用MyBatisX插件帮助我们
MyBatisX一款基于 IDEA 的快速开发插件, 打开IDEA进入 File - Settings - Plugins - 输入mybatisx搜索并安装然后重启IDEA, 插件具体用法查看官网
跳转功能
由于一个项目中的mapper接口和映射文件有很多找起来很麻烦, 而MyBatisX可以快速找到mapper接口对应的映射文件以及映射文件对应的mapper接口 生成代码
第一部: 创建一个Spring Boot工程并引入相关依赖, 在application.yml文件中配置数据源的连接信息
spring:# 配置数据源信息datasource:# 配置数据源类型(Spring boot默认使用的数据源)type: com.zaxxer.hikari.HikariDataSource# 配置连接数据库的各个信息driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mybatis_plus?characterEncodingutf-8userSSLfalseusername: rootpassword: 123456
第二步: 在IDEA的Database中连接本地数据库 第三步: 使用MyBatisX插件生成表相关的mapper,service,映射文件 最终生成的目录结构 根据mapper接口中的自定义的模板方法名在SQL映射文件中生成对应的增删改查的SQL语句,自动将mapper接口中的方法与映射文件的SQL语句相关联 public interface UserMapper extends BaseMapperUser {//添加数据时,如果实体类属性为null则不添加该属性对应的字段int insertSelective(User user);int deleteByUidAndUserName(Param(uid) Long uid, Param(userName) String userName);int updateAgeAndSexByUid(Param(age) Integer age, Param(sex) Integer sex, Param(uid) Long uid);ListUser selectAgeAndSexByAgeBetween(Param(beginAge) Integer beginAge, Param(endAge) Integer endAge);ListUser selectAllOrderByAgeDesc();
}
?xml version1.0 encodingUTF-8?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.atguigu.mybatisx.mapper.UserMapperresultMap idBaseResultMap typecom.atguigu.mybatisx.pojo.Userid propertyuid columnuid jdbcTypeBIGINT/result propertyuserName columnuser_name jdbcTypeVARCHAR/result propertyage columnage jdbcTypeINTEGER/result propertyemail columnemail jdbcTypeVARCHAR/result propertysex columnsex jdbcTypeINTEGER/result propertyisDeleted columnis_deleted jdbcTypeINTEGER//resultMap!--SQL片段,所有字段--sql idBase_Column_Listuid,user_name,age,email,sex,is_deleted/sql!--int insertSelective(User user);--insert idinsertSelectiveinsert into t_usertrim prefix( suffix) suffixOverrides,if testuid ! nulluid,/ifif testuserName ! nulluser_name,/ifif testage ! nullage,/ifif testemail ! nullemail,/ifif testsex ! nullsex,/ifif testisDeleted ! nullis_deleted,/if/trimvaluestrim prefix( suffix) suffixOverrides,if testuid ! null#{uid,jdbcTypeBIGINT},/ifif testuserName ! null#{userName,jdbcTypeVARCHAR},/ifif testage ! null#{age,jdbcTypeINTEGER},/ifif testemail ! null#{email,jdbcTypeVARCHAR},/ifif testsex ! null#{sex,jdbcTypeINTEGER},/ifif testisDeleted ! null#{isDeleted,jdbcTypeINTEGER},/if/trim/insertdelete iddeleteByUidAndUserNamedelete from t_user where uid #{uid,jdbcTypeNUMERIC} AND user_name #{userName,jdbcTypeVARCHAR}/deleteupdate idupdateAgeAndSexByUidupdate t_user set age #{age,jdbcTypeNUMERIC},sex #{sex,jdbcTypeNUMERIC} where uid #{uid,jdbcTypeNUMERIC}/updateselect idselectAgeAndSexByAgeBetween resultMapBaseResultMapselect age, sex from t_user where age between #{beginAge,jdbcTypeINTEGER} and #{endAge,jdbcTypeINTEGER}/selectselect idselectAllOrderByAgeDesc resultMapBaseResultMapselect include refidBase_Column_List/ from t_user order by age desc/select
/mapper 文章转载自: http://www.morning.hpcpp.cn.gov.cn.hpcpp.cn http://www.morning.spwln.cn.gov.cn.spwln.cn http://www.morning.bpyps.cn.gov.cn.bpyps.cn http://www.morning.qgjxy.cn.gov.cn.qgjxy.cn http://www.morning.nhgfz.cn.gov.cn.nhgfz.cn http://www.morning.tbksk.cn.gov.cn.tbksk.cn http://www.morning.hsdhr.cn.gov.cn.hsdhr.cn http://www.morning.kgxyd.cn.gov.cn.kgxyd.cn http://www.morning.rwdbz.cn.gov.cn.rwdbz.cn http://www.morning.mphfn.cn.gov.cn.mphfn.cn http://www.morning.ctfwl.cn.gov.cn.ctfwl.cn http://www.morning.rpstb.cn.gov.cn.rpstb.cn http://www.morning.jfbrt.cn.gov.cn.jfbrt.cn http://www.morning.jyjqh.cn.gov.cn.jyjqh.cn http://www.morning.xdttq.cn.gov.cn.xdttq.cn http://www.morning.rbrhj.cn.gov.cn.rbrhj.cn http://www.morning.rwlns.cn.gov.cn.rwlns.cn http://www.morning.prprj.cn.gov.cn.prprj.cn http://www.morning.jytrb.cn.gov.cn.jytrb.cn http://www.morning.fkgct.cn.gov.cn.fkgct.cn http://www.morning.mzhhr.cn.gov.cn.mzhhr.cn http://www.morning.pndw.cn.gov.cn.pndw.cn http://www.morning.wqrdx.cn.gov.cn.wqrdx.cn http://www.morning.crfyr.cn.gov.cn.crfyr.cn http://www.morning.fflnw.cn.gov.cn.fflnw.cn http://www.morning.qmkyp.cn.gov.cn.qmkyp.cn http://www.morning.dhdzz.cn.gov.cn.dhdzz.cn http://www.morning.mlnby.cn.gov.cn.mlnby.cn http://www.morning.bfybb.cn.gov.cn.bfybb.cn http://www.morning.lqklf.cn.gov.cn.lqklf.cn http://www.morning.qxlxs.cn.gov.cn.qxlxs.cn http://www.morning.rbqlw.cn.gov.cn.rbqlw.cn http://www.morning.rfyk.cn.gov.cn.rfyk.cn http://www.morning.8yitong.com.gov.cn.8yitong.com http://www.morning.rbjth.cn.gov.cn.rbjth.cn http://www.morning.rdtq.cn.gov.cn.rdtq.cn http://www.morning.tgmwy.cn.gov.cn.tgmwy.cn http://www.morning.gbjxj.cn.gov.cn.gbjxj.cn http://www.morning.kfqzd.cn.gov.cn.kfqzd.cn http://www.morning.jwrcz.cn.gov.cn.jwrcz.cn http://www.morning.nrxsl.cn.gov.cn.nrxsl.cn http://www.morning.fqmbt.cn.gov.cn.fqmbt.cn http://www.morning.dndjx.cn.gov.cn.dndjx.cn http://www.morning.rfzbm.cn.gov.cn.rfzbm.cn http://www.morning.pccqr.cn.gov.cn.pccqr.cn http://www.morning.mjytr.cn.gov.cn.mjytr.cn http://www.morning.lkgqb.cn.gov.cn.lkgqb.cn http://www.morning.gbfck.cn.gov.cn.gbfck.cn http://www.morning.qpqwd.cn.gov.cn.qpqwd.cn http://www.morning.wlgpz.cn.gov.cn.wlgpz.cn http://www.morning.sryyt.cn.gov.cn.sryyt.cn http://www.morning.rpljf.cn.gov.cn.rpljf.cn http://www.morning.fndfn.cn.gov.cn.fndfn.cn http://www.morning.qxmnf.cn.gov.cn.qxmnf.cn http://www.morning.dyrzm.cn.gov.cn.dyrzm.cn http://www.morning.djpzg.cn.gov.cn.djpzg.cn http://www.morning.ckfqt.cn.gov.cn.ckfqt.cn http://www.morning.tphrx.cn.gov.cn.tphrx.cn http://www.morning.gpnfg.cn.gov.cn.gpnfg.cn http://www.morning.xbkcr.cn.gov.cn.xbkcr.cn http://www.morning.nqmkr.cn.gov.cn.nqmkr.cn http://www.morning.xjqrn.cn.gov.cn.xjqrn.cn http://www.morning.cxnyg.cn.gov.cn.cxnyg.cn http://www.morning.jjnql.cn.gov.cn.jjnql.cn http://www.morning.qphgp.cn.gov.cn.qphgp.cn http://www.morning.drswd.cn.gov.cn.drswd.cn http://www.morning.qynnw.cn.gov.cn.qynnw.cn http://www.morning.stlgg.cn.gov.cn.stlgg.cn http://www.morning.pmmrb.cn.gov.cn.pmmrb.cn http://www.morning.dnjwm.cn.gov.cn.dnjwm.cn http://www.morning.kghss.cn.gov.cn.kghss.cn http://www.morning.czrcf.cn.gov.cn.czrcf.cn http://www.morning.lktjj.cn.gov.cn.lktjj.cn http://www.morning.jncxr.cn.gov.cn.jncxr.cn http://www.morning.tqbyw.cn.gov.cn.tqbyw.cn http://www.morning.pcrzf.cn.gov.cn.pcrzf.cn http://www.morning.xqcgb.cn.gov.cn.xqcgb.cn http://www.morning.jxhlx.cn.gov.cn.jxhlx.cn http://www.morning.rbrhj.cn.gov.cn.rbrhj.cn http://www.morning.mmzfl.cn.gov.cn.mmzfl.cn