Fluent MyBatis新建记录

1、代码生成

官网文档:https://gitee.com/fluent-mybatis/fluent-mybatis/wikis/

数据库结构表举例

-- 用户表可以添加一个点赞数字段,可选
drop table if exists social_user;
CREATE TABLE social_user (
user_id int(11) NOT NULL comment '用户id',
star_num int(11) NOT NULL default 0 COMMENT '点赞数量',
focus_num int(11) NOT NULL default 0 COMMENT '关注数量',
fan_num int(11) NOT NULL default 0 COMMENT '粉丝数量',
create_time timestamp not null default CURRENT_TIMESTAMP comment '创建时间',
update_time timestamp not null default CURRENT_TIMESTAMP comment '修改时间',
primary key(user_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户点赞表';

pom.xml中引入相关依赖

<properties>
        <java.version>1.8</java.version>
        <fluent-mybatis.version>1.8.7</fluent-mybatis.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 引入fluent-mybatis 运行依赖包, scope为compile -->
        <dependency>
            <groupId>com.github.atool</groupId>
            <artifactId>fluent-mybatis</artifactId>
            <version>${fluent-mybatis.version}</version>
        </dependency>
        <!-- 引入fluent-mybatis-processor, scope设置为provider 编译需要,运行时不需要 -->
        <dependency>
            <groupId>com.github.atool</groupId>
            <artifactId>fluent-mybatis-processor</artifactId>
            <scope>provided</scope>
            <version>${fluent-mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

设置代码生成文件,配置还是比较简单的

package com.zstu.social.utils;

import cn.org.atool.generator.FileGenerator;
import cn.org.atool.generator.annotation.Table;
import cn.org.atool.generator.annotation.Tables;
import org.junit.jupiter.api.Test;

public class EntityGenerator {
    // 数据源 url
    static final String url = "jdbc:mysql://localhost:3306/lamp_social?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8";
    // 数据库用户名
    static final String username = "root";
    // 数据库密码
    static final String password = "root";


    @Test
    public void generate() throws Exception {
        // 引用配置类,build方法允许有多个配置类
        FileGenerator.build(Empty.class);
    }

    @Tables(
            // 设置数据库连接信息
            url = url, username = username, password = password,
            // 设置entity类生成src目录, 相对于 user.dir
            srcDir = "src/main/java",
            // 设置entity类的package值
            basePack = "com.zstu.social.entity",
            // 设置dao接口和实现的src目录, 相对于 user.dir
            daoDir = "src/main/java",
            // 设置哪些表要生成Entity文件
            // tables = {@Table(value = {"social_comment","social_user","social_user_collect_video",
            // "social_user_focus","social_user_like_video","social_video"})},
            tables = {@Table(value = {"social_user"})},
            tablePrefix = "social_",
            logicDeleted = "deleted",
            gmtCreated = "create_time",
            gmtModified = "update_time"
    )
    static class Empty { //类名随便取, 只是配置定义的一个载体
    }
}

点击运行后,此时会生成相应的entity和dao包,此时dao包可能会出现找不到类的错误信息
请添加图片描述
需要对项目进行编译,完成后在target目录下会自动生成相应包
请添加图片描述
请添加图片描述
请添加图片描述

之后在application.yml配置相关数据

spring:
  # 应用名称
  application:
    name: social
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/lamp_social?useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&rewriteBatchedStatements=true


😄较为关键一点,需要设置数据源。我之前忘记配置就出错了,这里先配置默认数据源

package com.zstu.social.config;

import cn.org.atool.fluent.mybatis.spring.MapperFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationConfig {

    //  @Bean("dataSource")
    //  public DruidDataSource newDataSource() {
    //    return DataSourceCreator.create("datasource");
    //  }
    //
    //  @Bean
    //  public SqlSessionFactoryBean sqlSessionFactoryBean() throws Exception {
    //    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    //    bean.setDataSource(newDataSource());
    //    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    //    // 以下部分根据自己的实际情况配置
    //    // 如果有mybatis原生文件, 请在这里加载
    //    bean.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml"));
    //    /* bean.setMapperLocations(
    //    /*      new ClassPathResource("mapper/xml1.xml"),
    //    /*      new ClassPathResource("mapper/xml2.xml")
    //    /* );
    //    */
    //    org.apache.ibatis.session.Configuration configuration =
    //        new org.apache.ibatis.session.Configuration();
    //    configuration.setLazyLoadingEnabled(true);
    //    configuration.setMapUnderscoreToCamelCase(true);
    //    bean.setConfiguration(configuration);
    //    return bean;
    //  }

    // 定义fluent mybatis的MapperFactory
    @Bean
    public MapperFactory mapperFactory() {
        return new MapperFactory();
    }
}

最后在主函数上添加@MapperScan注解

@SpringBootApplication
@MapperScan({"com.zstu.social.entity.mapper"})
public class SocialApplication {

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

测试代码,成功

package com.zstu.social;

import com.zstu.social.entity.entity.UserEntity;
import com.zstu.social.entity.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SocialApplicationTests {

    @Autowired
    UserMapper userMapper;

    @Test
    void contextLoads() {
    }

    @Test
    public void testInsert() {
        UserEntity userEntity = new UserEntity()
                .setUserId(1)
                .setFanNum(2)
                .setFocusNum(3)
                .setStarNum(4);
        userMapper.insertWithPk(userEntity);
    }
}

2、错误分析

1、出现以下错误,需要引入mybatis的maven依赖

 Invalid default: public abstract java.lang.Class org.mybatis.spring.annotation.MapperScan.factoryBean()
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>

2、出现以下错误,代表没配置好数据源

Error invoking SqlProvider method 'public static java.lang.String cn.org.atool.fluent.mybatis.base.provider.SqlProvider.insertWithPk(java.util.Map,org.apache.ibatis.builder.annotation.ProviderContext)' with specify parameter 'class org.apache.ibatis.binding.MapperMethod$ParamMap'.  Cause: cn.org.atool.fluent.mybatis.exception.FluentMybatisException: Please add MapperFactory to spring container management: 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Fluent Mybatis是一个基于Mybatis的ORM框架,它提供了一种更加简洁、流畅的方式来操作数据库。通过使用Fluent Mybatis,开发者可以更轻松地进行数据库的增删改查操作。引用\[1\]中的代码片段展示了在使用Fluent Mybatis时需要引入的相关依赖。其中,fluent-mybatis是运行时的依赖包,而fluent-mybatis-processor是编译时的依赖包。 引用\[2\]中的代码片段展示了一个使用Fluent Mybatis进行数据插入的示例。在这个示例中,通过@Autowired注解注入了TestFluentMybatisMapper,然后使用该Mapper对象进行数据插入操作。 引用\[3\]是一篇关于Fluent Mybatis的文章,作者在文章中分享了自己学习该框架的过程,并展示了一些实用的代码。这篇文章介绍了Fluent Mybatis相对于其他ORM框架的优势,并提到了作者尝试去除一些项目中用不到的功能,以展示一些实用且有帮助的代码。 综上所述,Fluent Mybatis是一个基于Mybatis的ORM框架,它提供了一种简洁、流畅的方式来操作数据库。通过引入相关依赖并使用相应的Mapper对象,开发者可以轻松地进行数据库操作。 #### 引用[.reference_title] - *1* *3* [FluentMybatis 项目构建、代码生成(一) | FluentMybatis实践](https://blog.csdn.net/zhiweihongyan1/article/details/120848199)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [FluentMybatis 项目构建、代码生成(二) | FluentMybatis实践](https://blog.csdn.net/zhiweihongyan1/article/details/120854377)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值