MybatisPlus的使用及增删改查

第一步:配置依赖

<dependencies>
<!--mybatis-plues插件依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.3.1</version>
</dependency>

<!--Mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>

<!--连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>

<!--简化bean代码的工具包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>

二:MybatisPlus的用法
第一中用法Mybatis+MP 
首先创建子Module
log4j.properties:
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n
Mybatis实现查询User 第一步,编写mybatis-confifig.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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mp? useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQuerie s=true&useSSL=false"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="UserMapper.xml"/> </mappers> </configuration> 第二步,编写User实体对象:(这里使用lombok进行了进化bean操作) @Data @NoArgsConstructor @AllArgsConstructor public class User {   private Long id;   private String userName;   private String password;   private String name;   private Integer age;   private String email; } 第三步,编写UserMapper接口: public interface UserMapper {   List<User> findAll(); } 第四步,编写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="cn.itcast.mp.simple.mapper.UserMapper"> <select id="findAll" resultType="cn.itcast.mp.simple.pojo.User"> select * from tb_user </select> </mapper> 第五步,编写TestMybatis测试用例: public class TestMybatis { @Test public void testUserList() throws Exception{   String resource = "mybatis-config.xml";   InputStream inputStream = Resources.getResourceAsStream(resource);   SqlSessionFactory sqlSessionFactory = new   SqlSessionFactoryBuilder().build(inputStream);   SqlSession sqlSession = sqlSessionFactory.openSession();   UserMapper userMapper = sqlSession.getMapper(UserMapper.class);   List<User> list = userMapper.findAll();   for (User user : list) {   System.out.println(user);     }   } } 测试结果:
MybatisPlus的使用及增删改查

 Mybatis+MP实现查询User

第一步,将UserMapper继承BaseMapper,将拥有了BaseMapper中的所有方法:
 
public interface UserMapper extends BaseMapper<User> { List<User> findAll(); } 第二步,使用MP中的MybatisSqlSessionFactoryBuilder进程构建: public class TestMybatisPlus { @Test public void testUserList() throws Exception{   String resource = "mybatis-config.xml";   InputStream inputStream = Resources.getResourceAsStream(resource);   //这里使用的是MP中的MybatisSqlSessionFactoryBuilder   SqlSessionFactory sqlSessionFactory = new   MybatisSqlSessionFactoryBuilder().build(inputStream);   SqlSession sqlSession = sqlSessionFactory.openSession();   UserMapper userMapper = sqlSession.getMapper(UserMapper.class);   // 可以调用BaseMapper中定义的方法   List<User> list = userMapper.selectList(null);   for (User user : list) {   System.out.println(user);   } } 运行报错: 解决:在User对象中添加@TableName,指定数据库表名 由于使用了MybatisSqlSessionFactoryBuilder进行了构建,继承的BaseMapper中的方法就载入到了 SqlSession中,所以就可以直接使用相关的方法;   第二种方法 Spring+Mybatis+MP 第一步创建子模块 导入依赖
<!--定义Spring版本号-->
<properties>
<spring.version>5.1.6.RELEASE</spring.version>
</properties>

<!--引入Spring相关依赖-->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
实现查询User   第一步,编写jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3307/mp? useUnicode=true&amp;characterEncoding=utf8&amp;autoReconnect=true&amp;allowMultiQuerie s=true&amp;useSSL=false
jdbc.username=root
jdbc.password=root
第二步,编写applicationContext.xml   <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:*.properties"/> <!-- 定义数据源 -->     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
    <property name="driver" value="${jdbc.driver}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
      <property name="maxActive" value="10"/>       <property name="minIdle" value="5"/>     </bean>   <!--这里使用MP提供的sqlSessionFactory,完成了Spring与MP的整合-->   <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">     <property name="dataSource" ref="dataSource"/>   </bean>   <!--扫描mapper接口,使用的依然是Mybatis原生的扫描器-->   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">     <property name="basePackage" value="cn.itcast.mp.simple.mapper"/>   </bean> </beans> 第三步,编写User对象以及UserMapper接口: @Data @NoArgsConstructor @AllArgsConstructor @TableName("tb_user") public class User {   private Long id;   private String userName;   private String password;   private String name;   private Integer age;   private String email; } 第四步,编写测试用例: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class TestSpringMP {     @Autowired     private UserMapper userMapper;       @Test      public void testSelectList(){         List<User> users = this.userMapper.selectList(null);           for (User user : users) {           System.out.println(user);       }   } } 第三种SpringBoot+Mybatis+MP 使用SpringBoot将进一步的简化MP的整合,需要注意的是,由于使用SpringBoot需要继承parent,所以需要重新创 建工程,并不是创建子Module。 <!--SpringBoot版本-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.12.RELEASE</version>
</parent>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</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.1</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
log4j.properties: log4j.rootLogger=DEBUG,A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n 编写application.properties spring.application.name = itcast-mp-springboot spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false spring.datasource.username=root spring.datasource.password=root 编写pojo   @Data   @NoArgsConstructor   @AllArgsConstructor   @TableName("tb_user") public class User {     private Long id;     private String userName;     private String password;     private String name;     private Integer age;     private String email; } 编写mapper public interface UserMapper extends BaseMapper<User> { } 编写启动类 @MapperScan("cn.itcast.mp.mapper") //设置mapper接口的扫描包 @SpringBootApplication public class MyApplication {   public static void main(String[] args) {     SpringApplication.run(MyApplication.class, args);   } } 编写测试用例   //@RunWith(SpringRunner.class)
  @RunWith(SpringJUnit4ClassRunner.class)
 @SpringBootTest
public class UserMapperTest {     @Autowired   private UserMapper userMapper;   @Test     public void testSelect() {       List<User> userList = userMapper.selectList(null);         for (User user : userList) {           System.out.println(user);         }     } }   增加方法: 方法定义是Mybatisplus定义好的 测试用例 @RunWith(SpringRunner.class) @SpringBootTest public class UserMapperTest {     @Autowired     private UserMapper userMapper;     @Test    public void testInsert(){       User user = new User();       user.setAge(20);       user.setEmail("test@itcast.cn");       user.setName("曹操");       user.setUserName("caocao");       user.setPassword("123456");       int result = this.userMapper.insert(user); //返回的result是受影响的行数,并不是自增后的id       System.out.println("result = " + result);       System.out.println(user.getId()); //自增后的id会回填到对象中   } } 可以看到,数据已经写入到了数据库,但是,id的值不正确,我们期望的是数据库自增长,实际是MP生成了id的值 写入到了数据库。 如何设置id的生成策略呢? /** * 生成ID类型枚举类 * * @author hubin * @since 2015-11-10 */ @Getter public enum IdType { /** * 数据库ID自增 */ AUTO(0), /** * 该类型为未设置主键类型 */ NONE(1), /** * 用户输入ID * <p>该类型可以通过自己注册自动填充插件进行填充</p> */ INPUT(2), /* 以下3种类型、只有当插入对象ID 为空,才自动填充。 */ /** * 全局唯一ID (idWorker) */ ID_WORKER(3), /** * 全局唯一ID (UUID) */ UUID(4), MP支持的id策略: /** * 字符串全局唯一ID (idWorker 的字符串表示) */ ID_WORKER_STR(5); private final int key; IdType(int key) { this.key = key;   } } 修改User对象: @TableId(type = IdType.AUTO) //指定id类型为自增长 private Long id; @TableField 在MP中通过@TableField注解可以指定字段的一些属性,常常解决的问题有2个: 1、对象中的属性名和字段名不一致的问题(非驼峰) 2、对象中的属性字段在表中不存在的问题
@TableField(select = false)
@TableField(value = "email")//指定数据库表中的字段名
MybatisPlus的使用及增删改查

 

 

根据id更新 @RunWith(SpringRunner.class) @SpringBootTest public class UserMapperTest {   @Autowired   private UserMapper userMapper;     @Test public void testUpdateById() {       User user = new User();       user.setId(6L); //主键       user.setAge(21); //更新的字段     //根据id更新,更新不为null的字段     this.userMapper.updateById(user);   } } 根据条件更新
@Test
public void testUpdate(){
User user = new User();
user.setAge(20);
user.setPassword("88888");
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("user_name","zhangsan");
int result = this.userMapper.update(user,wrapper);//匹配user_name=zhangsan的用户数据
System.out.println("result =>"+result);
}

@Test
public void testUpdate2(){
UpdateWrapper<User> wrapper = new UpdateWrapper<>();
wrapper.set("age",21).set("password","99999")//更新的字段
.eq("user_name","zhangsan");
//根据条件做更新
int result = this.userMapper.update(null, wrapper);
System.out.println("result =>"+result);
}

根据id删除数据
@Test
public void testDeleteById(){
//根据id删除数据
int result = this.userMapper.deleteById(1L);
System.out.println("result =>"+result);
}

删除操作

deleteById

测试用例:

@Test
public void testDeleteById() {
    //执行删除操作
    int result = this.userMapper.deleteById(6L);
    System.out.println("result = " + result);
}

deleteByMap

@Test
public void testDeleteByMap(){
//根据id删除数据
HashMap<String, Object> map = new HashMap<>();
map.put("user_name","lisi");
map.put("password","123456");
//根据map删除数据,多条件之间是and关系
int result = this.userMapper.deleteByMap(map);
System.out.println("result =>"+result);
}
delete删除方法 public void testDeleteByMap() {   User user = new User();   user.setAge(20);   user.setName("张三");   //将实体对象进行包装,包装为操作条件   QueryWrapper<User> wrapper = new QueryWrapper<>(user);   int result = this.userMapper.delete(wrapper);   System.out.println("result = " + result); } deleteBatchIds @Test public void testDeleteByMap() {   //根据id集合批量删除   int result = this.userMapper.deleteBatchIds(Arrays.asList(1L,10L,20L));   System.out.println("result = " + result); }   批量查询方法 @Test public void testSelectBatchIds() {   //根据id集合批量查询   List<User> users = this.userMapper.selectBatchIds(Arrays.asList(2L, 3L, 10L));   for (User user : users) {   System.out.println(user);   } }   selectOne @Test public void testSelectOne() {     QueryWrapper<User> wrapper = new QueryWrapper<User>();     wrapper.eq("name", "李四");     //根据条件查询一条数据,如果结果超过一条会报错     User user = this.userMapper.selectOne(wrapper);     System.out.println(user); }   selectCount @Test public void testSelectCount() {   QueryWrapper<User> wrapper = new QueryWrapper<User>();   wrapper.gt("age", 23); //年龄大于23岁   //根据条件查询数据条数   Integer count = this.userMapper.selectCount(wrapper);   System.out.println("count = " + count); }   selectList @Test public void testSelectList() {     QueryWrapper<User> wrapper = new QueryWrapper<User>();     wrapper.gt("age", 23); //年龄大于23岁     //根据条件查询数据     List<User> users = this.userMapper.selectList(wrapper);    for (User user : users) {     System.out.println("user = " + user);   } }   selectPage /** * 分页插件 */ @Configuration @MapperScan("cn.itcast.mp.mapper") //设置mapper接口的扫描包 public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor();   } } 测试用例: @Test public void testSelectPage() {   QueryWrapper<User> wrapper = new QueryWrapper<User>();   wrapper.gt("age", 20); //年龄大于20岁   Page<User> page = new Page<>(1,1);   //根据条件查询数据   IPage<User> iPage = this.userMapper.selectPage(page, wrapper);   System.out.println("数据总条数:" + iPage.getTotal());   System.out.println("总页数:" + iPage.getPages());   List<User> users = iPage.getRecords();   for (User user : users) {   System.out.println("user = " + user);   } }     基本配置 MybatisPlus的使用及增删改查

 

 MybatisPlus的使用及增删改查

 

 MybatisPlus的使用及增删改查

 

 

 
上一篇:Spring学习笔记-Spring整合MyBatis


下一篇:MyBatis配置动态SQL语句基础