前言
MyBatis 最佳搭档,只做增强不做改变,为简化开发、提高效率而生。
简单用例
UserMapper.java
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
User.java
@TableName(value = "user")
public class User implements Serializable {@TableIdprivate int id;private String name;private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", age=" + age +'}';}
}
UserRepository.java
@Repository
public class UserRepository extends ServiceImpl<UserMapper, User> {
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.czy.mybatis.mapper.UserMapper"></mapper>
application.yml
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverpassword: xxxxusername: xxxurl: jdbc:mysql://xxxxx/mybatis?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
mybatis-plus:mapper-locations: classpath:./mapper/*Mapper.xmlconfiguration:log-impl: org.apache.ibatis.logging.stdout.StdOutImplmap-underscore-to-camel-case: true
ApplicationTest.java
@SpringBootTest(classes = Application.class)
public class ApplicationTest {@AutowiredUserRepository userRepository;@AutowiredUserMapper userMapper;// mybatisPlus 提供两种方式与数据库交互// 第一种: 延用mybatisMapper的方式进行数据交互// 第二种: mybatis-plus提供ServiceImpl实现类,相关的Repository继承ServiceImpl类,使用lambda的语法构造条件进行增删改查,// 还可以使用AbstractWrapper条件构造器进行条件增删改查// 这是通过继承ServiceImpl类@Testpublic void test1() {List<User> users = userRepository.lambdaQuery().eq(User::getId, 1).list();users.forEach(System.out::println);}// 这是通过mybatis Mapper的形式查询@Testpublic void test2() {User user = userMapper.selectById(1);System.out.println(user);}
}
用上mybatis-plus,你会发现mybatis-plus会提供自带的相关增删改查方法;
例如ServiceImpl提供saveBatch、saveOrUpdateBatch、updateBatchById、getOne、getOneOpt、removeById、updateById等相关方法
BaseMapper提供insert、deleteById、updateById、selectById等相关方法
具体相关使用可以参考mybatis-plus官网:https://baomidou.com/introduce/