在本文中,我们将详细介绍使用IDEA配置Mybatis-Plus框架图文详解的各个方面,并为您提供关于idea如何配置mybatis的相关解答,同时,我们也将为您带来关于02mybatis-plus配
在本文中,我们将详细介绍使用IDEA配置Mybatis-Plus框架图文详解的各个方面,并为您提供关于idea如何配置mybatis的相关解答,同时,我们也将为您带来关于02 mybatis-plus配置详解、day63( MYBATIS框架基础1:关于Mybatis框架,创建Mybatis-Spring工程,配置开发环境,基本使用,删除与修改数据)、Fluent Mybatis, 原生Mybatis, Mybatis Plus三者功能对比、Fluent Mybatis,原生Mybatis,Mybatis Plus三者功能对比的有用知识。
本文目录一览:- 使用IDEA配置Mybatis-Plus框架图文详解(idea如何配置mybatis)
- 02 mybatis-plus配置详解
- day63( MYBATIS框架基础1:关于Mybatis框架,创建Mybatis-Spring工程,配置开发环境,基本使用,删除与修改数据)
- Fluent Mybatis, 原生Mybatis, Mybatis Plus三者功能对比
- Fluent Mybatis,原生Mybatis,Mybatis Plus三者功能对比
使用IDEA配置Mybatis-Plus框架图文详解(idea如何配置mybatis)
这篇文章主要介绍了使用IDEA配置Mybatis-Plus框架,本文通过图文实例相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
目录
一、什么是Mybatis-Plus框架?
二、Mybatis有些什么特性?
三、IDEA创建SpringBoot项目
1、创建Spring Initializr模块
2、测试运行
3、引入依赖
4、创建数据库
5、配置数据库的链接文件
6、创建相关类和接口
7、测试
本文是以使用IDEA配置Mybatis-Plus框架作为简单的讲解。
所涉及到的应用:
IDEA2019
Mybatis-Plus框架
MysqL数据库
Maven3.6.3
jdk1.8
一、什么是Mybatis-Plus框架?
MyBatis-Plus(简称MP)是一个MyBatis的增强工具,提供给我们很多实用的插件。在Mybatis的基础上只做增强不做改变,为简化我们开发,提高工作效率而生。
二、Mybatis有些什么特性?
无侵入:MyBatis-Plus是在MyBatis的基础上增强的,而没有做任何的改变,所以在项目中引入MyBatis-Plus不会对你的现在的MyBatis构架有任何的影响.
依赖少:引入MyBatis-Plus要导入什么包呢?仅仅依赖MyBatis与MyBatis-Spring就可以了.
损耗小:启动之后,会自动注入基本的CRUD,性能基本无消耗,直接面向对象操作.
支持热加载:Mapper对应的XML支持热加载,对于简单的CRUD操作,甚至可以无XML启动.
支持代码生成:采用代码或Maven插件可快速生成Mapper、Model、Service、Controller层代码,支持模板引擎,更提供了超多的自定义配置让你使用.
三、IDEA创建SpringBoot项目
1、创建Spring Initializr模块
首先创建新项目按照如下图步骤操作:
接下来选择Spring Initializr项目,选择jdk版本,本文选择使用jdk1.8,然后点击next。如下图:
然后更改自己的包名(Group),以及项目名(Artifact),这里Java Version选择8,然后点击Next。效果图如下:
接下来选择Web项目,以及选择Spring Web框架载入,然后Next。效果图如下:
接下来修改自己的项目名称就好了,想起啥起啥,看自己,然后Finish。如下图:
基本上项目就配置完成了,一般第一次右下角会提示,都选择同意就好了,接下来就看网速了,网速好它自己配置的就快,基本上目录结构如下图:
2、测试运行
接下来找到MybitsplusApplication文件(这里发现mybatis单词拼错了,大家在接下来的时候要注意点),右键运行main方法测试一下是否配置成功,如果配置成功如下图:
运行成功图:
3、引入依赖
找到pom.xml,引入相关依赖,然后点击Import Change等待配置,这就得看你的网速了,金钱的力量!!
相关代码如下:
4.0.0org.springframework.bootspring-boot-starter-parent2.4.4com.yymybitsplus0.0.1-SNAPSHOTmybitsplusDemo project for Spring Boot1.8org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-testtestcom.baomidoumybatis-plus-boot-starter3.4.0MysqLmysql-connector-java5.1.49org.projectlomboklombok1.18.12providedorg.springframework.bootspring-boot-testorg.springframework.bootspring-boot-maven-plugin
4、创建数据库
这里可以根据自己创建的数据库来操作,我就是用我一直在用的测试数据库以及表,大家可以看自己,我的仅作参考就可以了,如下图:
插入数据:
5、配置数据库的链接文件
首先找到application.properties文件,在里面输入数据库的连接代码,这里面注意要更改成自己的数据库名称,效果图如下:
代码如下:
spring.datasource.url=jdbc:MysqL://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8 spring.datasource.driver-class-name=com.MysqL.jdbc.Driver spring.datasource.username=root spring.datasource.password=x5
6、创建相关类和接口
首先创建与表对应的实体类User,这里面Data注解可以方便我们创建实体类(不用编写get和set方法),如下图:
代码如下:
package com.yy.mybitsplus.pojo; import lombok.Data; @Data public class User { private Integer id; private String name; private Integer age; private String sex; }
编写Usermapper接口:
代码如下:
package com.yy.mybitsplus.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.yy.mybitsplus.pojo.User; import org.springframework.stereotype.Repository; @Repository public interface UserMapper extends BaseMapper { }
接下来在MybitsplusApplication文件中引入Mapper接口,如下图所示:
就不给代码了,很简单,但是大家打的时候要注意路径一定要打对!!
7、测试
接下来我们进行测试,打开test文件夹写的MybitsplusApplicationTests测试类,编写代码进行测试,要引入UserMapper接口注意,如下图所示:
代码如下:
package com.yy.mybitsplus; import com.yy.mybitsplus.mapper.UserMapper; import com.yy.mybitsplus.pojo.User; 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 class MybitsplusApplicationTests { @Autowired private UserMapper userMapper; @Test void contextLoads() { List users=userMapper.selectList(null); users.forEach(System.out::println); } }
接下来右键运行测试类,来看看效果,如下图:
测试成功!本文结束
到此这篇关于使用IDEA配置Mybatis-Plus框架的文章就介绍到这了,更多相关IDEA配置Mybatis-Plus框架内容请搜索小编以前的文章或继续浏览下面的相关文章希望大家以后多多支持小编!
02 mybatis-plus配置详解
前面实例中,mapper文件 继承 BaseMapper 类,直接调用BaseMapper 封装的方法;但是BaseMapper 封装的方法不一定都能满足业务,所以需要我们自定义实现
configLocations
configLocations即MyBatis 配置文件位置,如果有单独的 MyBatis 配置,请将其路径配置到 configLocations中。
- application.properties
spring.application.name = mp-springboot
spring.datasource.driver-class-name=com.MysqL.jdbc.Driver
spring.datasource.url=jdbc:MysqL://127.0.0.1:3306/mp
spring.datasource.username=root
spring.datasource.password=root
# Logger Config
logging.level.root: debug
#指定mybatis-config.xml的位置
mybatis-plus.config-location=classpath:mybatis-config.xml
- mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
mapperLocations
mapperLocations即MyBatis Mapper 所对应的 mapper配置 文件位置,如果在 Mapper 中有自定义方法(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置。
- application.properties
spring.application.name = mp-springboot
spring.datasource.driver-class-name=com.MysqL.jdbc.Driver
spring.datasource.url=jdbc:MysqL://127.0.0.1:3306/mp
spring.datasource.username=root
spring.datasource.password=root
# Logger Config
logging.level.root: debug
#指定mybatis-config.xml的位置
mybatis-plus.mapper-locations = classpath*:li/chen/com/mapper/*.xml
注意:
1 mapper配置文件UserMapper.xml在resources中路径与java对应的UserMapper.java 路径一致时,可不配mapper-locations;(注意resources中目录写法,如果报错找不到文件可以去target检查文件路径)
2 若UserMapper.xml在resources路径与UserMapper.java 路径不一致时,需要配置。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<!--mapper文件与xml温江放在同一文件夹下,需添加此配置-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
typeAliasesPackage
设置MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML 文件中可以直接使用类名,而不用使用全限定的类名(即 XML 中调用的时候不用包含包名)。
# 配置实体类的别名路径
mybatis-plus.type-aliases-package=li.chen.com.pojo
mapUnderscoreToCamelCase
是否开启自动驼峰命名规则(camel case)映射,即从数据库列名 A_COLUMN(下划线命名) 到经典 Java属性名 aColumn(驼峰命名) 的类似映射。
1 在application.properties中配置
#指定mybatis-config.xml的位置
# mybatis-plus.config-location=classpath:mybatis-config.xml 注释config‐location
#开启自动驼峰映射,注意:配置configuration.map‐underscore‐to‐camel‐case则不能配置config‐location
mybatis‐plus.configuration.map‐underscore‐to‐camel‐case=true
2 在mybatis-config.xml中配置(不注释config‐location)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--#开启自动驼峰映射,注意:配置configuration.map‐underscore‐to‐camel‐case则不能配置config‐location-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
实体类中,自动将驼峰格式字段映射数据库字段为下划线格式
项目文件
坐标文件
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>li.chen.com</groupId>
<artifactId>springboot_mybatisplus</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--简化代码的工具包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--mybatis-plus的springboot支持-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<!--MysqL驱动-->
<dependency>
<groupId>MysqL</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<!--mapper文件与xml温江放在同一文件夹下,需添加此配置-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
配置文件
application.properties
spring.application.name = mp_springboot
spring.datasource.driver-class-name=com.MysqL.jdbc.Driver
spring.datasource.url=jdbc:MysqL://127.0.0.1:3306/mp
spring.datasource.username=root
spring.datasource.password=root
# Logger Config
logging.level.root: debug
#指定mybatis-config.xml的位置
mybatis-plus.config-location=classpath:mybatis-config.xml
#指定mapper文件位置(注意,此配置时,根路径时在resources,若mapper.xml配置在java文件中,此配置无效,需要在pom文件中配置)
#mybatis-plus.mapper-locations = classpath*:li/chen/com/mapper/*.xml
# 配置实体类的别名路径
mybatis-plus.type-aliases-package=li.chen.com.pojo
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--#开启自动驼峰映射,注意:配置configuration.map‐underscore‐to‐camel‐case则不能配置config‐location-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
java文件
实体类
package li.chen.com.pojo;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
@Data //自动生成对应的get,set方法及构造方法
@TableName("tb_user") //对应数据库表名
public class User {
@TableId("id") //指定主键字段名
private Long id;
// @TableField("user_name") //指定对应字段名
private String userName;
@TableField("password")
private String passWord;
@TableField("name")
private String name;
@TableField("age")
private Integer age;
@TableField("email")
private String email;
@TableField("birthday")
private String birthday;
}
mapper文件
- UserMapper
package li.chen.com.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import li.chen.com.pojo.User;
public interface UserMapper extends BaseMapper<User> {
public User findById(Long id);
}
- UserMapper .xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="li.chen.com.mapper.UserMapper">
<select id="findById" resultType="user" parameterType="java.lang.Long">
select * from tb_user where id = #{id}
</select>
</mapper>
启动类
package li.chen.com;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
@MapperScan("li.chen.com.mapper")
@org.springframework.boot.autoconfigure.SpringBootApplication
public class SpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplication.class,args);
}
}
测试文件
package li.chen.com.mapper;
import li.chen.com.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBoottest;
import org.springframework.test.context.junit4.springrunner;
import java.util.List;
@RunWith(springrunner.class)
@SpringBoottest
public class UserMapperTest {
@Autowired
UserMapper userMapper;
@Test
public void TestSelect(){
//查询tb_user所有记录
List<User> users = userMapper.selectList(null);
System.out.println(users);
}
@Test
public void TestFindById(){
//查询指定id用户
User user = userMapper.findById(2L);
System.out.println(user);
}
}
运行查看
day63( MYBATIS框架基础1:关于Mybatis框架,创建Mybatis-Spring工程,配置开发环境,基本使用,删除与修改数据)
day63( MYBATIS框架基础1:关于Mybatis框架,创建Mybatis-Spring工程,配置开发环境,基本使用,删除与修改数据)
1.关于Mybatis框架
1.概念:
Mybatis的主要作用是快速实现对关系型数据库中的数据进行访问的框架
在原生的Java技术中,需要使用JDBC实现对数据库中的数据访问,执行过程繁琐且相对固定,使用框架可以有效的提高开发效率
2.创建Mybatis-Spring工程
前提: Mybatis可以不依赖于Spring等框架直接使用的,但是,就需要进行大量的配置,前期配置工作量较大,基于Spring框架目前是业内使用的标准之一,所以,通常会整合Spring与Mybatis,以减少配置
在创建工程时,创建普通的Maven工程即可(不需要选择特定的骨架)
1. 在pom.xml中添加几个依赖项
<dependencies>
<!-- Mybatis的依赖项:mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- Mybatis整合Spring的依赖项:mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- Spring的依赖项:spring-context-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.14</version>
</dependency>
<!-- Spring JDBC的依赖项:spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.14</version>
</dependency>
<!-- MysqL连接的依赖项:mysql-connector-java-->
<dependency>
<groupId>MysqL</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!-- 数据库连接池的依赖项:commons-dbcp2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.8.0</version>
</dependency>
<!-- JUnit测试的依赖项:junit-jupiter-api-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
2.创建测试类
可以在src/test/java下创建测试类,并编写测试方法,例如:
package cn.tedu.mybatis;
import org.junit.jupiter.api.Test;
public class MybatisTests {
@Test
public void contextLoads() {
System.out.println("MybatisTests.contextLoads()");
}
}
由于目前尚未编写实质的代码,以上测试代码也非常简单,应该是可以成功通过测试的,如果不能通过测试,必然是开发工具、开发环境、依赖项、项目创建步骤等问题
3.配置Mybatis的开发环境
1.创建数据库
登录MysqL控制台,创建名为mall_ams的数据库:
CREATE DATABASE mall_ams;
2.在IntelliJ IDEA中配置数据库视图:
http://doc.canglaoshi.org/doc/idea_database/index.html
通过数据库视图的Console面板创建数据表:
create table ams_admin (
id bigint unsigned auto_increment,
username varchar(50) default null unique comment '用户名',
password char(64) default null comment '密码(密文)',
nickname varchar(50) default null comment '昵称',
avatar varchar(255) default null comment '头像URL',
phone varchar(50) default null unique comment '手机号码',
email varchar(50) default null unique comment '电子邮箱',
description varchar(255) default null comment '描述',
is_enable tinyint unsigned default 0 comment '是否启用,1=启用,0=未启用',
last_login_ip varchar(50) default null comment '最后登录IP地址(冗余)',
login_count int unsigned default 0 comment '累计登录次数(冗余)',
gmt_last_login datetime default null comment '最后登录时间(冗余)',
gmt_create datetime default null comment '数据创建时间',
gmt_modified datetime default null comment '数据最后修改时间',
primary key (id)
) comment '管理员' charset utf8mb4;
3.创建datasource.properties配置文件
在src/main/resources下创建datasource.properties配置文件,用于配置连接数据库的参数,例如:
datasource.url=jdbc:MysqL://localhost:3306/mall_ams?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
datasource.driver=com.MysqL.cj.jdbc.Driver
datasource.username=root
datasource.password=root
提示:以上配置中的属性名称应该添加前缀,避免与系统环境变量冲突,例如在Windows操作系统中,username则表示登录系统的用户名
4.创建SpringConfig类
在cn.tedu.mybatis包下(不存在,则创建)创建SpringConfig类,读取以上配置文件:
@Configuration
@PropertySource("classpath:datasource.properties")
public class SpringConfig {
}
提示:@PropertySource是Spring框架的注解,用于读取properties类型的配置文件,读取到的值将存入到spring容器的Environment对象中
5. 测试方法中补充测试代码:
@Test
public void contextLoads() {
System.out.println("MybatisTests.contextLoads()");
AnnotationConfigApplicationContext ac
= new AnnotationConfigApplicationContext(SpringConfig.class);ConfigurableEnvironment environment = ac.getEnvironment();
System.out.println(environment.getProperty("datasource.url"));
System.out.println(environment.getProperty("datasource.driver"));
System.out.println(environment.getProperty("datasource.username"));System.out.println(environment.getProperty("datasource.password"));ac.close();
}
6. 在SpringConfig中配置一个DataSource对象:
@Configuration
@PropertySource("classpath:datasource.properties")
public class SpringConfig {
@Bean
public DataSource dataSource(Environment env) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl(env.getProperty("datasource.url"));
dataSource.setDriverClassName(env.getProperty("datasource.driver"));dataSource.setUsername(env.getProperty("datasource.username"));dataSource.setPassword(env.getProperty("datasource.password"));return dataSource;
}
}
7.测试方法中补充测试代码:
@Test
public void testConnection() throws Exception {
AnnotationConfigApplicationContext ac
= new AnnotationConfigApplicationContext(SpringConfig.class);DataSource dataSource = ac.getBean("dataSource"
, DataSource.class);Connection connection = dataSource.getConnection();
System.out.println(connection);
ac.close();
}
4.Mybatis的基本使用
1.作用:
当使用Mybatis实现数据访问时,主要:
编写数据访问的抽象方法
配置抽象方法对应的sql语句
2. 关于抽象方法:
必须定义在某个接口中,这样的接口通常使用Mapper作为名称的后缀,例如AdminMapper
Mybatis框架底层将通过接口代理模式来实现
方法的返回值类型:
如果要执行的数据操作是增、删、改类型的,统一使用int作为返回值类型,表示“受影响的行数” ,也可以使用void,但是不推荐
如果要执行的是查询操作,返回值类型只需要能够装载所需的数据即可
方法的名称:自定义,不要重载,建议风格如下:
插入数据使用insert
作为方法名称中的前缀或关键字
删除数据使用delete
作为方法名称中的前缀或关键字
更新数据使用update
作为方法名称中的前缀或关键字
查询数据时:
如果是统计,使用count
作为方法名称中的前缀或关键字
如果是单个数据,使用get
或find
作为方法名称中的前缀或关键字
如果是列表,使用list
作为方法名称中的前缀或关键字
如果操作数据时有条件,可在以上前缀或关键字右侧添加by字段名
,例如deleteById
方法的参数列表:取决于需要执行的sql语句中有哪些参数,如果有多个参数,可将这些参数封装到同一个类型中,使用封装的类型作为方法的参数类型
例如:假设当需要实现“插入一条管理员数据”,则需要执行的sql语句大致是
insert into ams_admin (username, password, nickname, avatar,phone,email, description, is_enable, last_login_ip, login_count,
gmt_last_login, gmt_create, gmt_modified) values (?,?,? ... ?);
由于以上sql语句中的参数数量较多,则应该将它们封装起来,则在cn.tedu.mybatis包下创建Admin类,声明一系列的属性,对应以上各参数值:
package cn.tedu.mybatis;
import java.time.LocalDateTime;
public class Admin {
private String username; private String password;
private String nickname; private String avatar;
private String phone; private String email;
private String description; private Integer isEnable;
private String lastLoginIp; private Integer loginCount;
private LocalDateTime gmtLastLogin; private LocalDateTime gmtCreate;
private LocalDateTime gmtModified;
// Setters & Getters // toString()
}
在cn.tedu.mybatis包下创建mapper.AdminMapper接口,并在接口中添加“插入1条管理员数据”的抽象方法:
package cn.tedu.mybatis.mapper;
import cn.tedu.mybatis.Admin;
public interface AdminMapper {
int insert(Admin admin);
}
所有用于Mybatis处理数据的接口都必须被Mybatis识别,有2种做法
在每个接口上添加@Mapper注解
【推荐】在配置类上添加@MapperScan注解,指定接口所在的根包
例如,在SpringConfig上添加配置@MapperScan:
@Configuration
@PropertySource("classpath:datasource.properties")
@MapperScan("cn.tedu.mybatis.mapper")
public class SpringConfig {
// ... ...
}
注意:因为Mybatis会扫描以上配置的包,并自动生成包中各接口中的代理对象,所以,千万不要放其它接口文件
接下来,需要配置抽象方法对应的sql语句,这些sql语句推荐配置在XML文件中
可以从 http://doc.canglaoshi.org/config/Mapper.xml.zip下载到XML文件。在项目的src/main/resources下创建mapper文件夹,并将下载得到的XML文件复制到此文件夹中,重命名为AdminMapper.xml。
打开XML文件夹,进行配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 根节点必须是mapper -->
<!-- 根节点的namespace属性用于配置此XML对应哪个接口 -->
<mapper namespace="cn.tedu.mybatis.mapper.AdminMapper">
<!-- 根据需要执行的sql语句的种类选择需要配置的节点名称-->
<!-- 配置sql的节点的id属性取值为抽象方法名称 -->
<!-- 在节点内部配置sql语句 -->
<!-- sql语句中的参数值使用 #{} 格式的占位符表示 -->
<insert id="insert">
insert into ams_admin (
username, password, nickname, avatar,
phone, email, description, is_enable,
last_login_ip, login_count, gmt_last_login, gmt_create,
gmt_modified
) values (
#{username}, #{password}, #{nickname}, #{avatar},
#{phone}, #{email}, #{description}, #{isEnable},
#{lastLoginIp}, #{loginCount}, #{gmtLastLogin}, #{gmtCreate},#{gmtModified}
)
</insert>
</mapper>
最后,还需要将DataSource配置给Mybatis框架,并且,为Mybatis配置这些XML文件的路径,这2项配置都将通过配置sqlSessionfactorybean来完成
先在datasource.properties中补充一条配置:
mybatis.mapper-locations=classpath:mapper/AdminMapper.xml
在配置类中创建sqlSessionfactorybean类型的对象:
@Bean
public sqlSessionfactorybean sqlSessionfactorybean(DataSource dataSource,@Value("${mybatis.mapper-locations}") Resource mapperLocations){sqlSessionfactorybean sqlSessionfactorybean = new sqlSessionfactorybean();sqlSessionfactorybean.setDataSource(dataSource);
sqlSessionfactorybean.setMapperLocations(mapperLocations);
return sqlSessionfactorybean;
}
在测试类中补充测试方法,以检验是否可以通过调用AdminMapper的insert()方法插入数据:
@Test public void testInsert() { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);AdminMapper adminMapper = ac.getBean(AdminMapper.class); Admin admin = new Admin(); admin.setUsername("admin001"); admin.setPassword("12345678"); adminMapper.insert(admin); ac.close(); }
如果某数据的id是自动编号,当需要获取新增的数据的id时,需要先使得插入的数据类型中有id对应的属性,则在Admin类中添加id属性:
public class Admin { private Long id; // 原有其它属性及Setter & Getter // 补充id的Setter & Getter // 重新生成toString() }
接下来,在节点配置2个属性,分别是useGeneratedKeys和keyProperty:
<insert id="insert" useGeneratedKeys="true" keyProperty="id">原有代码 </insert>
当配置完成后,Mybatis执行此插入数据的操作后,会将自动编号的id赋值到参数Admin admin的id属性中,以上keyProperty指的就是将自动编号的值放回到参数对象的哪个属性中!
5.删除与修改数据
1.目标(根据id删除某一条数据 )
根据id删除某一条数据
2.执行
sql
delete from ams_admin where id=?
在AdminMapper接口中添加抽象方法:
int deleteById(Long id);
在AdminMapper.xml中配置以上抽象方法映射的sql语句:
<delete id="deleteById"> delete from ams_admin where id=#{id} </delete>
编写并执行测试:
@Test public void testDeleteById() { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class); AdminMapper adminMapper = ac.getBean(AdminMapper.class); Long id = 12L; int rows = adminMapper.deleteById(id); // System.out.println("删除完成,受影响的行数=" + rows); if (rows == 1) { System.out.println("删除成功"); } else { System.out.println("删除失败,尝试删除的数据(id=" + id + ")不存在!"); } ac.close(); }
3.目标(根据 id修改某一条数据 )
4.执行
sql
update ams_admin set password=? where id=?
在AdminMapper接口中添加抽象方法:
int updatePasswordById(@Param("id") Long id, @Param("password") String password);
提示:在默认情况下,当Java程序源代码(.java文件)经过编译后,所有局部的量的名称都会丢失,为使得配置sql语句时可根据指定的名称使用方法中的参数值,需要在方法的各参数前添加@Param以指定名称
如果方法的参数只有1个,则可以不使用@Param指定名称,因为Mybatis可以直接找到此参数的值
在AdminMapper.xml中配置以上抽象方法映射的sql语句:
<update id="updatePasswordById"> update ams_admin set password=#{password} where id=#{id}</update>
提示:以上占位符中的名称是通过@Param注解指定的名称,而不是抽象方法的参数名称
编写并执行测试:
@Test public void testUpdatePasswordById() { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class); AdminMapper adminMapper = ac.getBean(AdminMapper.class); Long id = 12L; String password = "000000"; int rows = adminMapper.updatePasswordById(id, password); if (rows == 1) { System.out.println("修改密码成功"); } else { System.out.println("修改密码失败,尝试访问的数据(id=" + id + ")不存在!"); } ac.close(); }
Fluent Mybatis, 原生Mybatis, Mybatis Plus三者功能对比
使用fluent mybatis可以不用写具体的xml文件,通过java api可以构造出比较复杂的业务sql语句,做到代码逻辑和sql逻辑的合一。不再需要在Dao中组装查询或更新操作,在xml或mapper中再组装参数。那对比原生Mybatis, Mybatis Plus或者其他框架,FluentMybatis提供了哪些便利呢?
需求场景设置
我们通过一个比较典型的业务需求来具体实现和对比下,假如有学生成绩表结构如下:
create table `student_score`
(
id bigint auto_increment comment ''主键ID'' primary key,
student_id bigint not null comment ''学号'',
gender_man tinyint default 0 not null comment ''性别, 0:女; 1:男'',
school_term int null comment ''学期'',
subject varchar(30) null comment ''学科'',
score int null comment ''成绩'',
gmt_create datetime not null comment ''记录创建时间'',
gmt_modified datetime not null comment ''记录最后修改时间'',
is_deleted tinyint default 0 not null comment ''逻辑删除标识''
) engine = InnoDB default charset=utf8;
现在有需求:
统计2000年三门学科(''英语'', ''数学'', ''语文'')及格分数按学期,学科统计最低分,最高分和平均分, 且样本数需要大于1条,统计结果按学期和学科排序
我们可以写SQL语句如下
select school_term,
subject,
count(score) as count,
min(score) as min_score,
max(score) as max_score,
avg(score) as max_score
from student_score
where school_term >= 2000
and subject in (''英语'', ''数学'', ''语文'')
and score >= 60
and is_deleted = 0
group by school_term, subject
having count(score) > 1
order by school_term, subject;
那上面的需求,分别用fluent mybatis, 原生mybatis 和 Mybatis plus来实现一番。
三者实现对比
使用fluent mybatis 来实现上面的功能
我们可以看到fluent api的能力,以及IDE对代码的渲染效果。
换成mybatis原生实现效果
- 定义Mapper接口
public interface MyStudentScoreMapper {
List<Map<String, Object>> summaryScore(SummaryQuery paras);
}
- 定义接口需要用到的参数实体 SummaryQuery
@Data
@Accessors(chain = true)
public class SummaryQuery {
private Integer schoolTerm;
private List<String> subjects;
private Integer score;
private Integer minCount;
}
- 定义实现业务逻辑的mapper xml文件
<select id="summaryScore" resultType="map" parameterType="cn.org.fluent.mybatis.springboot.demo.mapper.SummaryQuery">
select school_term,
subject,
count(score) as count,
min(score) as min_score,
max(score) as max_score,
avg(score) as max_score
from student_score
where school_term >= #{schoolTerm}
and subject in
<foreach collection="subjects" item="item" open="(" close=")" separator=",">
#{item}
</foreach>
and score >= #{score}
and is_deleted = 0
group by school_term, subject
having count(score) > #{minCount}
order by school_term, subject
</select>
- 实现业务接口(这里是测试类, 实际应用中应该对应Dao类)
@RunWith(SpringRunner.class)
@SpringBootTest(classes = QuickStartApplication.class)
public class MybatisDemo {
@Autowired
private MyStudentScoreMapper mapper;
@Test
public void mybatis_demo() {
// 构造查询参数
SummaryQuery paras = new SummaryQuery()
.setSchoolTerm(2000)
.setSubjects(Arrays.asList("英语", "数学", "语文"))
.setScore(60)
.setMinCount(1);
List<Map<String, Object>> summary = mapper.summaryScore(paras);
System.out.println(summary);
}
}
总之,直接使用mybatis,实现步骤还是相当的繁琐,效率太低。那换成mybatis plus的效果怎样呢?
换成mybatis plus实现效果
mybatis plus的实现比mybatis会简单比较多,实现效果如下
如红框圈出的,写mybatis plus实现用到了比较多字符串的硬编码(可以用Entity的get lambda方法部分代替字符串编码)。字符串的硬编码,会给开发同学造成不小的使用门槛,个人觉的主要有2点:
- 字段名称的记忆和敲码困难
- Entity属性跟随数据库字段发生变更后的运行时错误
其他框架,比如TkMybatis在封装和易用性上比mybatis plus要弱,就不再比较了。
生成代码编码比较
fluent mybatis生成代码设置
public class AppEntityGenerator {
static final String url = "jdbc:mysql://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8";
public static void main(String[] args) {
FileGenerator.build(Abc.class);
}
@Tables(
/** 数据库连接信息 **/
url = url, username = "root", password = "password",
/** Entity类parent package路径 **/
basePack = "cn.org.fluent.mybatis.springboot.demo",
/** Entity代码源目录 **/
srcDir = "spring-boot-demo/src/main/java",
/** Dao代码源目录 **/
daoDir = "spring-boot-demo/src/main/java",
/** 如果表定义记录创建,记录修改,逻辑删除字段 **/
gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted",
/** 需要生成文件的表 ( 表名称:对应的Entity名称 ) **/
tables = @Table(value = {"student_score"})
)
static class Abc {
}
}
mybatis plus代码生成设置
public class CodeGenerator {
static String dbUrl = "jdbc:mysql://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8";
@Test
public void generateCode() {
GlobalConfig config = new GlobalConfig();
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL)
.setUrl(dbUrl)
.setUsername("root")
.setPassword("password")
.setDriverName(Driver.class.getName());
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig
.setCapitalMode(true)
.setEntityLombokModel(false)
.setNaming(NamingStrategy.underline_to_camel)
.setColumnNaming(NamingStrategy.underline_to_camel)
.setEntityTableFieldAnnotationEnable(true)
.setFieldPrefix(new String[]{"test_"})
.setInclude(new String[]{"student_score"})
.setLogicDeleteFieldName("is_deleted")
.setTableFillList(Arrays.asList(
new TableFill("gmt_create", FieldFill.INSERT),
new TableFill("gmt_modified", FieldFill.INSERT_UPDATE)));
config
.setActiveRecord(false)
.setIdType(IdType.AUTO)
.setOutputDir(System.getProperty("user.dir") + "/src/main/java/")
.setFileOverride(true);
new AutoGenerator().setGlobalConfig(config)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(
new PackageConfig()
.setParent("com.mp.demo")
.setController("controller")
.setEntity("entity")
).execute();
}
}
FluentMybatis特性一览
三者对比总结
看完3个框架对同一个功能点的实现, 各位看官肯定会有自己的判断,笔者这里也总结了一份比较。
- | Mybatis Plus | Fluent Mybatis |
---|---|---|
代码生成 | 生成 Entity | 生成Entity, 再通过编译生成 Mapper, Query, Update 和 SqlProvider |
Generator易用性 | 低 | 高 |
和Mybatis的共生关系 | 需替换原有的SqlSessionFactoryBean | 对Mybatis没有任何修改,原来怎么用还是怎么用 |
动态SQL构造方式 | 应用启动时, 根据Entity注解信息构造动态xml片段,注入到Mybatis解析器 | 应用编译时,根据Entity注解,编译生成对应方法的SqlProvider,利用mybatis的Mapper上@InsertProvider @SelectProvider @UpdateProvider注解关联 |
动态SQL结果是否容易DEBUG跟踪 | 不容易debug | 容易,直接定位到SQLProvider方法上,设置断点即可 |
动态SQL构造 | 通过硬编码字段名称, 或者利用Entity的get方法的lambda表达式 | 通过编译手段生成对应的方法名,直接调用方法即可 |
字段变更后的错误发现 | 通过get方法的lambda表达的可以编译发现,通过字段编码的无法编译发现 | 编译时便可发现 |
不同字段动态SQL构造方法 | 通过接口参数方式 | 通过接口名称方式, FluentAPI的编码效率更高 |
语法渲染特点 | 无 | 通过关键变量select, update, set, and, or可以利用IDE语法渲染, 可读性更高 |
Fluent Mybatis,原生Mybatis,Mybatis Plus三者功能对比
本文主要介绍了Fluent Mybatis,原生Mybatis,Mybatis Plus三者功能对比,分享给大家,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
目录
三者实现对比
使用fluent mybatis 来实现上面的功能
换成mybatis原生实现效果
换成mybatis plus实现效果
生成代码编码比较
fluent mybatis生成代码设置
mybatis plus代码生成设置
FluentMybatis特性一览
三者对比总结
Fluent Mybatis介绍和源码
使用fluent mybatis可以不用写具体的xml文件,通过java api可以构造出比较复杂的业务sql语句,做到代码逻辑和sql逻辑的合一。
不用再需要在Dao中组装查询或更新操作,在xml或mapper中再组装次参数。
那对比原生Mybatis, Mybatis Plus或者其他框架,FluentMybatis提供了哪些便利呢?
我们通过一个比较典型的业务需求来具体实现和对比下,假如有学生成绩表结构如下:
create table `student_score` ( id bigint auto_increment comment '主键ID' primary key, student_id bigint not null comment '学号', gender_man tinyint default 0 not null comment '性别, 0:女; 1:男', school_term int null comment '学期', subject varchar(30) null comment '学科', score int null comment '成绩', gmt_create datetime not null comment '记录创建时间', gmt_modified datetime not null comment '记录最后修改时间', is_deleted tinyint default 0 not null comment '逻辑删除标识' ) engine = InnoDB default charset=utf8;
现在有需求:
统计2000年三门学科(‘英语', ‘数学', ‘语文')及格分数按学期,学科统计最低分,最高分和平均分,
且样本数需要大于1条,统计结果按学期和学科排序
我们可以写sql语句如下
select school_term, subject, count(score) as count, min(score) as min_score, max(score) as max_score, avg(score) as max_score from student_score where school_term >= 2000 and subject in ('英语', '数学', '语文') and score >= 60 and is_deleted = 0 group by school_term, subject having count(score) > 1 order by school_term, subject;
那上面的需求,分别用fluent mybatis, 原生mybatis 和 Mybatis plus来实现一番。
三者实现对比
使用fluent mybatis 来实现上面的功能
具体代码
我们可以看到fluent api的能力,以及IDE对代码的渲染效果。
换成mybatis原生实现效果
定义Mapper接口
public interface MyStudentscoreMapper { List> summaryscore(SummaryQuery paras); }
定义接口需要用到的参数实体 SummaryQuery
@Data @Accessors(chain = true) public class SummaryQuery { private Integer schoolTerm; private List subjects; private Integer score; private Integer minCount; }
定义实现业务逻辑的mapper xml文件
select school_term, subject, count(score) as count, min(score) as min_score, max(score) as max_score, avg(score) as max_score from student_score where school_term >= #{schoolTerm} and subject in #{item} and score >= #{score} and is_deleted = 0 group by school_term, subject having count(score) > #{minCount} order by school_term, subject
实现业务接口(这里是测试类, 实际应用中应该对应Dao类)
@RunWith(springrunner.class) @SpringBoottest(classes = QuickStartApplication.class) public class MybatisDemo { @Autowired private MyStudentscoreMapper mapper; @Test public void mybatis_demo() { // 构造查询参数 SummaryQuery paras = new SummaryQuery() .setSchoolTerm(2000) .setSubjects(Arrays.asList("英语", "数学", "语文")) .setscore(60) .setMinCount(1); List> summary = mapper.summaryscore(paras); System.out.println(summary); } }
总之,直接使用mybatis,实现步骤还是相当的繁琐,效率太低。
那换成mybatis plus的效果怎样呢?
换成mybatis plus实现效果
mybatis plus的实现比mybatis会简单比较多,实现效果如下
但正如红框圈出的,写mybatis plus实现用到了比较多字符串的硬编码(可以用Entity的get lambda方法部分代替字符串编码)。字符串的硬编码,会给开发同学造成不小的使用门槛,个人觉的主要有2点:
字段名称的记忆和敲码困难
Entity属性跟随数据库字段发生变更后的运行时错误
其他框架,比如TkMybatis在封装和易用性上比mybatis plus要弱,就不再比较了。
生成代码编码比较
fluent mybatis生成代码设置
public class AppEntityGenerator { static final String url = "jdbc:MysqL://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8"; public static void main(String[] args) { FileGenerator.build(Abc.class); } @Tables( /** 数据库连接信息 **/ url = url, username = "root", password = "password", /** Entity类parent package路径 **/ basePack = "cn.org.fluent.mybatis.springboot.demo", /** Entity代码源目录 **/ srcDir = "spring-boot-demo/src/main/java", /** Dao代码源目录 **/ daoDir = "spring-boot-demo/src/main/java", /** 如果表定义记录创建,记录修改,逻辑删除字段 **/ gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted", /** 需要生成文件的表 ( 表名称:对应的Entity名称 ) **/ tables = @Table(value = {"student_score"}) ) static class Abc { } }mybatis plus代码生成设置
public class CodeGenerator { static String dbUrl = "jdbc:MysqL://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8"; @Test public void generateCode() { GlobalConfig config = new GlobalConfig(); DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setDbType(DbType.MysqL) .setUrl(dbUrl) .setUsername("root") .setPassword("password") .setDriverName(Driver.class.getName()); StrategyConfig strategyConfig = new StrategyConfig(); strategyConfig .setCapitalMode(true) .setEntityLombokModel(false) .setNaming(NamingStrategy.underline_to_camel) .setColumnNaming(NamingStrategy.underline_to_camel) .setEntityTableFieldAnnotationEnable(true) .setFieldPrefix(new String[]{"test_"}) .setInclude(new String[]{"student_score"}) .setLogicDeleteFieldName("is_deleted") .setTableFillList(Arrays.asList( new TableFill("gmt_create", FieldFill.INSERT), new TableFill("gmt_modified", FieldFill.INSERT_UPDATE))); config .setActiveRecord(false) .setIdType(IdType.AUTO) .setoutputDir(System.getProperty("user.dir") + "/src/main/java/") .setFileOverride(true); new AutoGenerator().setGlobalConfig(config) .setDataSource(dataSourceConfig) .setStrategy(strategyConfig) .setPackageInfo( new PackageConfig() .setParent("com.mp.demo") .setController("controller") .setEntity("entity") ).execute(); } }
FluentMybatis特性一览
三者对比总结
看完3个框架对同一个功能点的实现, 各位看官肯定会有自己的判断,笔者这里也总结了一份比较。
-
Mybatis Plus
Fluent Mybatis
代码生成
生成 Entity, Mapper, Wrapper等文件, 并且Generator很好用
只生成Entity, 再通过编译生成 Mapper, Query, Update 和 sqlProvider
和Mybatis的共生关系
需要替换原有的sqlSessionfactorybean
对Mybatis没有任何修改,原来怎么用还是怎么用
动态sql构造方式
应用启动时, 根据Entity注解信息构造动态xml片段,注入到Mybatis解析器
应用编译时,根据Entity注解,编译生成对应方法的sqlProvider,利用mybatis的Mapper上@InsertProvider @SelectProvider @UpdateProvider注解关联
动态sql结果是否容易DEBUG跟踪
不容易debug
容易,直接定位到sqlProvider方法上,设置断点即可
动态sql构造
通过硬编码字段名称, 或者利用Entity的get方法的lambda表达式
通过编译手段生成对应的方法名,直接调用方法即可
字段变更后的错误发现
通过get方法的lambda表达的可以编译发现,通过字段编码的无法编译发现
编译时便可发现
不同字段动态sql构造方法
通过接口参数方式
通过接口名称方式, FluentAPI的编码效率更高
语法渲染特点
无
通过关键变量select, update, set, and, or可以利用IDE语法渲染, 可读性更高
Fluent Mybatis介绍和源码
Fluent Mybatis文档&示例
Fluent Mybatis源码, github
到此这篇关于Fluent Mybatis,原生Mybatis,Mybatis Plus三者功能对比的文章就介绍到这了,更多相关Fluent Mybatis,原生Mybatis,Mybatis Plus内容请搜索小编以前的文章或继续浏览下面的相关文章希望大家以后多多支持小编!
我们今天的关于使用IDEA配置Mybatis-Plus框架图文详解和idea如何配置mybatis的分享就到这里,谢谢您的阅读,如果想了解更多关于02 mybatis-plus配置详解、day63( MYBATIS框架基础1:关于Mybatis框架,创建Mybatis-Spring工程,配置开发环境,基本使用,删除与修改数据)、Fluent Mybatis, 原生Mybatis, Mybatis Plus三者功能对比、Fluent Mybatis,原生Mybatis,Mybatis Plus三者功能对比的相关信息,可以在本站进行搜索。
本文标签: