Mybatis Plus是对Mybatis的增强!

官网:https://baomidou.com/

入门案例

引入maven依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>最新版本 3.5.2</version>
    </dependency>

启动类添加@MapperScan

@SpringBootApplication
@MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

编写 Mapper 包下的 UserMapper接口,继承 BaseMapper<T>

public interface UserMapper extends BaseMapper<User> {

}

实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("User")
public class User implements Serializable {
    @TableId(value = "id",type = IdType.AUTO)
    private Integer id;
    @TableField(value = "new_hope",exist = true)
    private String newHope;
    private String name;
    private int age;
    private boolean isman;
    private static final long serialVersionUID = 1L;
}

测试案例

@SpringBootTest
public class SampleTest {

    // 注入mapper
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        // 测试查询功能
        List<User> userList = userMapper.selectList(null);
        Assert.assertEquals(5, userList.size());
        userList.forEach(System.out::println);
    }

}

特别说明

Mybaits Plus 还可以额外提供IService接口。(Mapper层继承BaseMapper<ORM-Obj>不能少)

自己的Service直接继承IService方便减少Mapper层的CRUD内容。https://baomidou.com/pages/49cc81/#service-crud-%E6%8E%A5%E5%8F%A3

但是IService有自己的子类实现,如:ServiceImpl。有子类实现直接用子类即可呗。

使用方式:

  1. Impl层继承ServiceImpl 参数填写Mapper接口名、操作的实体类名。
  2. Mapper接口继承BaseMapper<实体类名>
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zanglikun.springdataredisdemo.mapper.UserMapper;
import com.zanglikun.springdataredisdemo.pojo.User;
import com.zanglikun.springdataredisdemo.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserviceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public String saveUser() {
        User user = new User("zanglikun", 12, true);
        // 直接调用save方法
        boolean save = save(user);
        if (save == true) {
            System.out.println("插入成功");
        }
        return "OK";
    }
}

Mapper层,什么都不需要写,仅需继承BaseMapper<T>即可

@Mapper
public interface UserMapper extends BaseMapper<User> {
}
特殊说明:
上述文章均是作者实际操作后产出。烦请各位,请勿直接盗用!转载记得标注原文链接:www.zanglikun.com
第三方平台不会及时更新本文最新内容。如果发现本文资料不全,可访问本人的Java博客搜索:标题关键字。以获取全部资料 ❤