Spirngboot 集成 mybatis-plus

依賴


dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
//    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.2'
    implementation('com.baomidou:mybatis-plus-boot-starter:3.1.0')
    implementation('com.baomidou:mybatis-plus-generator:3.1.0')

    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'mysql:mysql-connector-java'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}
  • 主要是mybatis-plus-boot-starter這個(gè)注解,里面包含了mybatis,不需要重復(fù)引入

配置文件

server:
  port: 10000


spring:
  datasource:
    url: jdbc:mysql://localhost:3307/JLCredit
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
  #mapper的xml文件所在
  mapper-locations: classpath:mapper/*.xml
  configuration:
    #開啟駝峰命名
    map-underscore-to-camel-case: true
  • 普通的連接mysql數(shù)據(jù)庫
  • mybatis若要在xml文件中寫sql,需要注意xml文件位置,這里是直接放在了resources/mapper路徑下

開啟事務(wù)

@EnableTransactionManagement
@SpringBootApplication
public class MybatisPlusApplication {

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

}


使用

配置

@Configuration
public class MyBatisPlusConfig {

    /**
     * mybatis-plus SQL執(zhí)行效率插件【生產(chǎn)環(huán)境可以關(guān)閉】
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }
    /**
     * 分頁插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

}
  • performanceInterceptor在開啟之后每次使用mybatis-plus會(huì)打印出執(zhí)行的sql語句
  • paginationInterceptor則是分頁工具

實(shí)體類

@Data
@TableName("user")
public class UserEntity implements Serializable {

    @TableId
    private String username;

    private String id;

    private String name;

    private String phone;


    @TableField(fill = FieldFill.INSERT) // 創(chuàng)建記錄的時(shí)候需要填充
    private Date createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE) // 創(chuàng)建和修改的時(shí)候都需要填充
    private Date updateTime;

}
  • 實(shí)體類@TableName映射表名
  • @TableField的自動(dòng)填充通過以下配置實(shí)現(xiàn)創(chuàng)建時(shí)間和修改時(shí)間的插入與更新:
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

}

mapper

@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {

    UserEntity getUserById(@Param("id") String id);

    IPage<UserEntity> getUserPage(Page<?> page);

}

server

public interface UserServer extends IService<UserEntity> {


     UserEntity getUserById(String id);

     IPage<UserEntity> getUserPage(Page<UserEntity> page);
     
     void saveUser(UserEntity userEntity);
}

serverImpl

@Service
public class UserServerImpl extends ServiceImpl<UserMapper, UserEntity> implements UserServer {


    @Override
    public UserEntity getUserById(String id) {
        return baseMapper.getUserById(id);
    }

    @Override
    public IPage<UserEntity> getUserPage(Page<UserEntity> page) {
        return baseMapper.getUserPage(page);
    }


    @Transactional
    @Override
    public void saveUser(UserEntity userEntity) {
        save(userEntity);
    }

}
  • 在編寫完實(shí)體類,以及實(shí)體類對(duì)應(yīng)的mapper,server,serverImpl之后,就可以使用這個(gè)server對(duì)該實(shí)體所映射的表進(jìn)行增刪改查的操作,mybatisplus提供的操作類基本滿足了所有單表的需求,但是多表查詢依舊建議自己寫個(gè)sql
  • 自己寫原生sql有兩種,一種是通過@Select,@Updata,@Delete,@Insert在mapper中寫,要么就編寫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="com.ladyishenlong.mybatisplus.mapper.UserMapper">


    <select id="getUserById" resultType="com.ladyishenlong.mybatisplus.model.UserEntity">
        select i.name from user i where i.id = #{id}
    </select>

    <select id="getUserPage" resultType="com.ladyishenlong.mybatisplus.model.UserEntity">
                select i.name from user i
    </select>

</mapper>

查詢

    @Autowired
    private UserServer userServer;


    @GetMapping
    public Object test() {

        //分頁查詢
        IPage<UserEntity> page = new Page<>();
        page.setCurrent(0); //當(dāng)前頁
        page.setSize(1);    //每頁條數(shù)
        userServer.page(page, new QueryWrapper<UserEntity>().lambda()
                .eq(UserEntity::getId, "666"));

        //xml分頁查詢
        Page<UserEntity> userEntityPage = new Page<>();
        userEntityPage.setCurrent(0);
        userEntityPage.setSize(1);
        IPage<UserEntity> userEntityIPage = userServer.getUserPage(userEntityPage);


        //xml語句
        userServer.getUserById("666");
        //自動(dòng)生成查詢
        userServer.list(new QueryWrapper<UserEntity>().lambda()
                .eq(UserEntity::getId, "666"));


        return userEntityIPage;

    }


  • 這里的分頁也可用于xml中自己寫的查詢語句

插入

    @Autowired
    private UserServer userServer;


    @GetMapping("/test2")
    public Object test2() {

        //插入數(shù)據(jù),可以添加事務(wù)
        UserEntity userEntity = new UserEntity();
        userEntity.setId("2500");
        userEntity.setName("黑魔導(dǎo)");
        userEntity.setPhone("2500");
        userEntity.setUsername("2500");
        userServer.saveUser(userEntity);
        
        return "";
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 前言 MyBatis是一個(gè)優(yōu)秀的持久層ORM框架,它對(duì)jdbc的操作數(shù)據(jù)庫的過程進(jìn)行封裝,使開發(fā)者只需要關(guān)注SQL...
    AI喬治閱讀 641評(píng)論 0 5
  • MyBatis是一個(gè)優(yōu)秀的持久層ORM框架,它對(duì)jdbc的操作數(shù)據(jù)庫的過程進(jìn)行封裝,使開發(fā)者只需要關(guān)注SQL 本身...
    樓蘭King閱讀 681評(píng)論 0 5
  • 1.mybatis 中 #{}和 ${}的區(qū)別是什么? 1. #將傳入的數(shù)據(jù)都當(dāng)成一個(gè)字符串,會(huì)對(duì)自動(dòng)傳入的數(shù)據(jù)加...
    久伴_不離閱讀 3,837評(píng)論 0 4
  • 今天抖音粉絲破千了。 意味著可以帶貨了。 從18年開始玩抖音,最早是在日本做了2個(gè)打鼓的視頻放到賬號(hào)上,直到今年2...
    云間大彭閱讀 274評(píng)論 0 3
  • 原創(chuàng)/人杰地靈 季秋正陽 淡卻幕夜清涼 游步叢樓林園 沐浴暖溫陽光 足間落葉斑點(diǎn) 眸掃綠蔥染黃 頓覺流年易逝 青絲...
    人杰地靈_2eeb閱讀 1,049評(píng)論 8 46