MyBatis-Plus的使用
MyBatis-Plus学习笔记
一、MySQL
1、创建表
DROP TABLE IF EXISTS user;CREATE TABLE user
(id BIGINT(20) NOT NULL COMMENT '主键ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',age INT(11) NULL DEFAULT NULL COMMENT '年龄',email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',PRIMARY KEY (id)
);
2、插入数据
DELETE FROM user;INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
二、代码生成器
1、导入依赖
<!--Web-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql-->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok-->
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
</dependency>
<!--mybatisPlus-->
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.3.1</version>
</dependency>
<!--MybatisPlus代码生成器 依赖-->
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.4.1</version>
</dependency>
<!--velocity依赖-->
<dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.0</version>
</dependency>
<!--swagger依赖-->
<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version>
</dependency>
<!--工具包--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.3</version></dependency>
<!--安全框架Sa-ToKen--><dependency><groupId>cn.dev33</groupId><artifactId>sa-token-spring-boot-starter</artifactId><version>1.24.0</version></dependency><!--=================================================================================-->
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins><!--=======================扫描在java包下.xml文件所需==============================================--><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include><include>**/*.properties</include></includes></resource><resource><directory>src/main/resources</directory></resource></resources><!--=================================================================================--></build>
说明:我们使用mybatis-plus 可以节省我们大量的代码,尽量不要同时导入mybatis和mybatis-plus因为版本有差异!
2、.yml文件所需配置
连接数据库!这一步和mybatis相同!
spring:
# profiles:
# active: devdatasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/studentmanager?useUnicode=trun&characterEncoding=utf-8&useSSl=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8username: rootpassword: 123456server:port: 8013#=================================以上为代码生成器所需配置===============================# 配置日志 (默认控制台输出)
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#此处配置扫描.XML文件,注意的配合依赖包一起用mapper-locations: classpath:com/roleToken/GWL/mapper/xml/*.xmltype-aliases-package: com.roleToken.GWL.entity#mybatis:
# mapper-locations: classpath:mapper/*.xml
# type-aliases-package: com.example.demo3.pojo
# configuration:
# map-underscore-to-camel-case: true
server:port: 8013#配置(mybatisplus3.4.3.1版本)
mybatis-plus:# 配置逻辑删除global-config:db-config:logic-delete-field: deleted # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置实体类字段上加上@TableLogic注解)logic-delete-value: 1 # 逻辑已删除值(默认为 1)logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
3、代码生成器文件
代码生成器位置
package com.example.myplus;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;public class MyBatis {public static void main(String[] args) {// 需要构建一个 代码自动生成器 对象AutoGenerator mpg = new AutoGenerator();// 1、全局配置GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir");//获取项目路径gc.setOutputDir(projectPath+"/src/main/java");//设置路径gc.setAuthor("郭文龙"); //设置作者gc.setOpen(false);//是否打开资源管理器gc.setFileOverride(false);// 是否覆盖原来生成的gc.setServiceName("%sService"); // 去Service的I前缀gc.setIdType(IdType.AUTO);//ID设为自增gc.setDateType(DateType.ONLY_DATE);//日期格式gc.setSwagger2(true);//配置swaggermpg.setGlobalConfig(gc);//全局配置//2、设置数据源DataSourceConfig dsc = new DataSourceConfig();//==============================修改数据库名称========dsc.setUrl("jdbc:mysql://localhost:3306/studentmanager?useUnicode=trun&characterEncoding=utf-8&useSSl=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("123456");dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc);//3、包的配置PackageConfig pc = new PackageConfig();//只需要改实体类名字 和包名 还有 数据库配置即可pc.setModuleName("GWL");//模块名//===========================修改位置信息============pc.setParent("com.example.myplus");//模块生成位置pc.setEntity("entity");pc.setMapper("mapper");pc.setService("service");pc.setController("controller");mpg.setPackageInfo(pc);//全局配置//4、策略配置StrategyConfig strategy = new StrategyConfig();//=================================修改表名=============strategy.setInclude("user");//设置要映射的表名strategy.setNaming(NamingStrategy.underline_to_camel);//下划线转驼峰命名strategy.setColumnNaming(NamingStrategy.underline_to_camel);//下划线转驼峰命名strategy.setEntityLombokModel(true);// 自动lombok;strategy.setLogicDeleteFieldName("deleted");//逻辑删除字段// 时间自动填充配置TableFill createTime = new TableFill("create_time", FieldFill.INSERT);TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);ArrayList<TableFill> tableFills = new ArrayList<>();tableFills.add(createTime); tableFills.add(updateTime);strategy.setTableFillList(tableFills);// 乐观锁strategy.setVersionFieldName("version");strategy.setRestControllerStyle(true);//controller是Restful风格strategy.setControllerMappingHyphenStyle(true);// localhost:8080/hello_id_2mpg.setStrategy(strategy);//全局配置//执行全局配置mpg.execute();}
}
4、测试增删查改
mapper层加注解
@Repository//代表持久层
@Mapper
public interface UserMapper extends BaseMapper<User> {}//或启动下
@MapperScan("com/roleToken/GWL/mapper")
增删查改
package com.example.myplus;import com.example.myplus.GWL.entity.User;
import com.example.myplus.GWL.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;@SpringBootTest
class MyPlusApplicationTests {//继承了BaseMapper, 所有的方法都来自己父类//我们也可以编写自己的扩展方法@Autowiredprivate UserMapper userMapper;@Testvoid contextLoads() {//参数是一个Wrapper , 条件构造器,这里我们先不用 --null//查询全部用户List<User> users = userMapper.selectList(null);
// 遍历输出users.forEach(System.out::println);}@Testpublic void testInsert(){// 插入(添加)用户,主要数据库里主键设置为自增User user = new User();user.setName("郭文龙");user.setAge(18);user.setEmail("2335806038@qq.com");
// 更新个数int result = userMapper.insert(user);System.out.println(result);System.out.println(user);}//测试更新@Testpublic void testUpdate(){// 修改用户信息User user = new User();user.setId(2L);user.setName("阿峧不是山交");// 注意:updateById()参数是 一个对象!,这里输出的还是更新个数int i = userMapper.updateById(user);System.out.println(i);}//删除操作,通过id@Testpublic void testDeleteById(){//通过id删除this.userMapper.deleteById(1);//通过多个id,一次删除多个数据ArrayList list = new ArrayList();list.add(2);list.add(3);this.userMapper.deleteBatchIds(list);}//测试条件删除,通过map@Testpublic void testDeleteByMap(){HashMap<String, Object> map = new HashMap<>();map.put("name","z1111113f");this.userMapper.deleteByMap(map);}}
三、controller层常用方法
1、增删查改
package com.vuespringboot.GWL.controller;import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vuespringboot.GWL.entity.User;
import com.vuespringboot.GWL.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/user")
public class UserController {@AutowiredUserMapper userMapper;@GetMapping("/myTongJi")//查找全部员工public List<User> list() {return userMapper.selectList(null);}@PostMapping("/login")//登录验证=====================================登录验证public int login(@RequestBody User user) {User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getName, user.getName()).eq(User::getPassword, user.getPassword()));if (res==null){return -1;}else {return 1;}}@GetMapping("/emps") //还能加默认值============================分页与查询public Page<User> testPage(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "6") Integer pageSize,@RequestParam(defaultValue = "") String search){//参数一:当前页,======参数二:页面大小//获取该页Page<User> page = new Page<User>(pageNum,pageSize);LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
// 如果关键字为空则查询全部,不为空就进行模糊查询,加了这个name和id为空,分页查询也能查,好像是这样if (StrUtil.isNotBlank(search)){wrapper.like(User::getName,search);wrapper.like(User::getName,search).or().like(User::getId,search);}//查询该页Page<User> userPage = userMapper.selectPage(page, wrapper);//::为获取类中属性的语法糖
// List<User> userList = userPage.getRecords();return userPage;}@PostMapping("/emp")//接收添加完成的成员信息=================添加员工public void jiaUser(@RequestBody User user) {userMapper.insert(user);}@DeleteMapping("/emp/{id}")//接收删除请求=================删除员工public void chuUse(@PathVariable long id) {userMapper.deleteById(id);}@PutMapping("/gai")//接收修改完成的信息====================修改员工public void GaiUser(@RequestBody User user) {userMapper.updateById(user);}
}
2、文件传输
// 好像是获取端口号@Value("${server.port}")private String port;private static final String ip = "http://localhost";@PostMapping("/file")//文件上传=============================文件上传public Result<?> file(@RequestPart("files") MultipartFile files) throws IOException {// 获取文件String fileName = files.getOriginalFilename();
// 方法一:存储路径//files.transferTo(new File("D:\\我下载的\\IDEA\\过程文件\\VueSpringBoot\\src\\main\\resources\\files\\"+fileName));// 先生成一个唯一标识符,防止相同名称的文件会覆盖String flag = IdUtil.fastSimpleUUID();//方法二
// user.dir 项目根路径String filePath = System.getProperty("user.dir") + "/src/main/resources/files/" + flag + "_" + fileName;
// 把文件写入上传的路径FileUtil.writeBytes(files.getBytes(), filePath);
// 返回下载图片的URL(地址)return Result.success(ip + ":" + port + "/user/" + flag);}// 通过唯一标识确认具体文件@GetMapping("/{flag}")//文件下载=====================文件下载public void getFile(@PathVariable String flag, HttpServletResponse response) {OutputStream os;//新建一个输出流
// 获取文件存放的路径String filePast = System.getProperty("user.dir") + "/src/main/resources/files/";
// 查询该路径下的所有文件的名称List<String> fileNames = FileUtil.listFileNames(filePast);
// 找到与唯一标识一致的文件String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");try {// 如果那个文件存在,则证明可以被下载if (StrUtil.isNotEmpty(fileName)) {response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));response.setContentType("application/octet-stream");
// 通过文件路径读取文件字节流byte[] bytes = FileUtil.readBytes(filePast + fileName);
// 通过输出流返回文件(字节流出去到浏览器,通过response相应,所以没有返回值类型)os = response.getOutputStream();os.write(bytes);os.flush();os.close();}} catch (Exception e) {System.out.println("文件下载失败");}}
三、扩展部分
1、主键生成策略
// @TableId(type = IdType.AUTO)//主键自增,数据库的字段也必须设置为自增
// @TableId(type = IdType.NONE)//该类型为未设置主键类型
// @TableId(type = IdType.INPUT)//手动输入id
//以下2种类型、只有当插入对象ID 为空,才自动填充。
// @TableId(type = IdType.ASSIGN_UUID)//UUID,全局唯一。主键类型为 String,缺点字符串逐渐不易检索
// @TableId(type = IdType.ASSIGN_ID)//默认使用雪花算法 ,主键类型为 Long 或 Stringprivate Long id;
//实体类中定义ID处
注意:
实体类字段上 @TableId(type = IdType.AUTO)
,数据库字段一定要是自增!
2、分页查询、解决跨域
MybatisPlusConfig.java加入分页插件配置
package com.example.myplus.config;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//=================结果跨域问题
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;//扫描我们的mapper文件夹
@MapperScan("com/example/myplus")
@Configuration
@EnableTransactionManagement//事务
public class MyPlusConfig implements WebMvcConfigurer {//mybatisPlus3.4.3.1写法@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();//注册乐观锁插件interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//分页插件 我们使用的是mysql数据库interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}//======================跨域问题@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET","HEAD","POST","PUT","DELETE","REQUEST").allowCredentials(false).maxAge(3600).allowedHeaders("*");}}
测试方法
//分页查询(需要在MybatisPlusConfig类配置)
@Test
public void testPage(){//参数一:当前页,======参数二:页面大小//获取该页Page<User> page = new Page<User>(2,3);//查询该页Page<User> userPage = this.userMapper.selectPage(page, null);//获得记录List<User> userList = userPage.getRecords();for (User user : userList) {System.out.println(user);}
}
还提供了其他方法
3、逻辑删除
**物理删除:从数据库中直接移除 **
逻辑删除:在数据库中没有被移除,而是通过一个变量让他生效!deleted=0 --> deleted=1
管理员可以查看被删除的记录!防止数据的丢失!类似于回收站!
1、在数据库表中增加一个deleted字段(默认值为0)
2、实体类中添加属性
@TableLogic // 逻辑删除private Integer deleted;
3、配置(mybatisplus3.4.3.1版本)
mybatis-plus: # 配置逻辑删除 global-config: db-config: logic-delete-field: deleted # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置实体类字段上加上@TableLogic注解) logic-delete-value: 1 # 逻辑已删除值(默认为 1) logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
结果走的是更新操作,不是删除操作,会将deleted字段设置为1,逻辑上删除
4、乐观锁&悲观锁
MybatisPlusConfig.java加入配置
package com.example.myplus.config;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;//扫描我们的mapper文件夹
@MapperScan("com/example/myplus")
@Configuration
@EnableTransactionManagement//事务
public class MyPlusConfig {//mybatisPlus3.4.3.1写法@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();//注册乐观锁插件interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//分页插件 我们使用的是mysql数据库interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}}
测试
//测试乐观锁(需要在MybatisPlusConfig类配置)
@Test
public void testOptimisticLockerInner(){//乐观锁进行修改前会先查询,取出version的值,//然后进行修改更新信息的时候会比较version的值是否和之前查询的时候的version值一致//如果是一致则修改更新信息并且version的值+1//如果不是则修改信更新息失败//线程一User user = this.userMapper.selectById(1L);user.setName("zfStart1111");user.setEmail("123123123");//线程二,模拟插队操作User user2 = this.userMapper.selectById(1L);user2.setName("zfStart2222");user2.setEmail("22222");this.userMapper.updateById(user2);//有乐观锁的存在,在被其他线程插队的情况下,修改更新信息失败this.userMapper.updateById(user);
}
5、时间属性自动填充
创建时间 . 修改时间! 这些个操作都是自动化完成的,我们不希望手动更新!
阿里巴巴开发手册:所有的数据库表:gmt_create .gmt_modified几乎所有的表都要配置上!而且需要自动化!
方式一
方式一:数据库级别
1.在表中新增字段 create_time , update_time
2.再次测试插入方法,我们需要先把实体类同步
private Data creatTime;private Data updateTime;
方式二
方式二:代码级别
1.删除数据库默认值
将自动给出默认值打的钩子去掉
2.实体类字段属性上添加注解
//记住用util包下的Date!!
//字段添加填充内容
//添加用户时添加时间(需要在MyMetaObjectHandler类配置)
@TableField(fill = FieldFill.INSERT)
private Date createTime;//添加用户或更新用户时添加时间(需要在MyMetaObjectHandler类配置)
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;1
3.编写处理器来处理这个注解
package com.codeyuaiiao.handler;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;import java.util.Date;@Slf4j
@Component //把处理器加到IOC容器中
public class MyMetaObjectHandler implements MetaObjectHandler {//插入时的填充策略@Overridepublic void insertFill(MetaObject metaObject) {log.info("Start insert fill.... ");this.setFieldValByName("createTime",new Date(),metaObject);this.setFieldValByName("updateTime",new Date(),metaObject);}//更新时的填充策略@Overridepublic void updateFill(MetaObject metaObject) {log.info("Start update fill.... ");this.setFieldValByName("updateTime",new Date(),metaObject);}
}
之后更新插入操作会自动填充操作时间
6、执行 SQL 分析打印
我们在平时的开发中,会遇到一些慢sql.
MP也提供了性能分析插件,如果超过这个时间就停止运行!
四、条件构造器
十分重要:wrapper
我们写一些复杂的sql就可以使用它来代替!
package com.example.myplus;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.myplus.GWL.entity.User;
import com.example.myplus.GWL.mapper.UserMapper;
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
public class WrapperTest {@Autowiredprivate UserMapper userMapper;//条件查询@Testvoid testGe() {//查询name和邮箱不为空,年龄大于12岁的用户
// 这步好像必须要QueryWrapper<User> wrapper = new QueryWrapper<>();//和map有点相似
// 添加查询条件wrapper.isNotNull("name").isNotNull("email").ge("age", 12);//大于等于 greater是大于,equal是等于userMapper.selectList(wrapper).forEach(System.out::println);}//条件查询@Testpublic void testEq() {//查询名字QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.eq("name", "Sandy");
// 这个查询只能查一个人的,如果查询结果个数不唯一会报红User user = this.userMapper.selectOne(wrapper);System.out.println(user);}//查询年龄在10-20岁之间@Testvoid testBetWeen() {QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.between("age", 10, 20);//区间List<User> userList = this.userMapper.selectList(wrapper);//查询到的用户集合for (User user : userList) {System.out.println(user);}}//模糊查询===============================================================@Testpublic void testLike() {QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.likeLeft("name", "龙"); //name like '%zf'List<User> userList = this.userMapper.selectList(wrapper);for (User user : userList) {System.out.println(user);}}//内查询(可以多表联查)@Testpublic void testInSql() {QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.inSql("id", "select id from user where id <20");List<User> users = this.userMapper.selectList(wrapper);for (User user : users) {System.out.println(user);}}//排序@Testpublic void testOrderBy() {QueryWrapper<User> wrapper = new QueryWrapper<>();//通过id进行降序排序wrapper.orderByDesc("id");List<User> users = this.userMapper.selectList(wrapper);for (User user : users) {System.out.println(user);}}
}
MyBatis-Plus的使用相关推荐
- mybatis查询报错:com.mysql.cj.exceptions.DataConversionException: Cannot determine value type from string
mybatis查询报错: com.mysql.cj.exceptions.DataConversionException: Cannot determine value type from strin ...
- MyBatis的插入后获得主键的方式
需求: 使用MyBatis往MySQL数据库中插入一条记录后,需要返回该条记录的自增主键值. 方法: 在mapper中指定keyProperty属性,示例如下: <insert id=" ...
- mybatis使用注解开发
mybatis使用注解开发 面向接口编程 在之前我们是通过面向对象编程,但是在真正开发的时候我们会选择面向接口编程. 根本原因 : 解耦 , 可拓展 , 提高复用 , 分层开发中 , 上层不用管具体的 ...
- mybatis ResultMap
ResultMap 解决属性名和字段的名称不一致的问题. 查询为null的问题 创建java实体类: public class User {private int id; //idprivate St ...
- mybatis配置文件解析
mybatis配置文件解析 mybatis核心配置文件`mybatis-config.xml文件. mybatis的配置文件包含了会深深影响mybatis行为的设置和属性信息. 能配置的内容: con ...
- mybatis CRUD操作
mybatis CRUD操作 select select标签是mybatis最常用的标签之一. select语句有很多属性可以详细的配置每一天sql语句. id 命名空间唯一的标识. 接口中的方法名与 ...
- java mybatis基础
java mybatis基础 1.1 什么是mybatis? mybatis是一个优秀的持久层框架. 避免几乎所有的JDBC代码和手动设置参数以及获取结果集的过程. 可以使用简单的xml或者注解来配置 ...
- mybatis的资源过滤错误及xml文件编码错误
mybatis 解决maven项目内资源过滤的问题 写的配置文件无法被导出或者生效的问题. 解决方案: <build><resources><resource>&l ...
- Mybatis传递多个参数的4种方式
现在大多项目都是使用Mybatis了,但也有些公司使用Hibernate.使用Mybatis最大的特性就是sql需要自己写,而写sql就需要传递多个参数.面对各种复杂的业务场景,传递参数也是一种学问. ...
- SpringBoot (五) :SpringBoot整合mybatis
说在前面 mybatis刚开始使用的时候比较麻烦,需要各种配置文件.实体类.dao层映射关联.还有一大推其它配置.初期开发了generator可以根据表结果自动生产实体类.配置文件和dao层代码,可以 ...
最新文章
- 单身萌妹纸手把手教你用产品思维追女生
- 去掉一键还原 开机按k键
- CodeForces - 850C Arpa and a game with Mojtaba(博弈+sg函数)
- 几个方便编程的C++特性
- 企业服务总线全双工异步通信机
- 在Ubuntu 上怎么连接装有iOS 7的iPhone或iPad
- unserialize用法
- 深度优先搜索-和为某数的所有组合
- Python中新式类和经典类的区别,钻石继承
- 《啊哈!算法》-第 4 章:万能的搜索 - 宝岛冒险
- python 画ks曲线_风控模型—区分度评估指标(KS)深入理解应用
- Javascript 调用MSAgent(调用office助手显示动画)
- linux安装时找不到硬盘分区,在安装linux时出现找不到硬盘如何解决
- 程序员为什么要转行项目经理
- 5分绩点转4分_泪目!老詹儿子凌晨5点起身训练,科比女儿4点,魔术师叹息退出群聊...
- 一次性奖金是否选择并入综合所得测算表
- 字符串中大小写转换输出
- 精通移动App测试实战:技术、工具和案例
- P1558 色板游戏
- 使用python和PyQt5编写爬取百度图片的界面工具