### Database Schema Setup Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/04-advanced-generator SQL script to create the fluent_mybatis schema and the user and receiving_address tables. ```sql create schema fluent_mybatis; use fluent_mybatis; drop table if exists user; CREATE TABLE user ( id bigint(21) unsigned auto_increment primary key COMMENT '主键id', avatar varchar(255) DEFAULT NULL COMMENT '头像', account varchar(45) DEFAULT NULL COMMENT '账号', password varchar(45) DEFAULT NULL COMMENT '密码', user_name varchar(45) DEFAULT NULL COMMENT '名字', birthday datetime DEFAULT NULL COMMENT '生日', e_mail varchar(45) DEFAULT NULL COMMENT '电子邮件', phone varchar(20) DEFAULT NULL COMMENT '电话', bonus_points bigint(21) DEFAULT 0 COMMENT '会员积分', status varchar(32) DEFAULT NULL COMMENT '状态(字典)', gmt_create datetime DEFAULT NULL COMMENT '创建时间', gmt_modified datetime DEFAULT NULL COMMENT '更新时间', is_deleted tinyint(2) DEFAULT 0 COMMENT '是否逻辑删除' ) ENGINE = InnoDB CHARACTER SET = utf8 COMMENT = '用户表'; drop table if exists receiving_address; CREATE TABLE receiving_address ( id bigint(21) unsigned auto_increment primary key COMMENT '主键id', user_id bigint(21) NOT NULL COMMENT '用户id', province varchar(50) DEFAULT NULL COMMENT '省份', city varchar(50) DEFAULT NULL COMMENT '城市', district varchar(50) DEFAULT NULL COMMENT '区', detail_address varchar(100) DEFAULT NULL COMMENT '详细住址', gmt_create datetime DEFAULT NULL COMMENT '创建时间', gmt_modified datetime DEFAULT NULL COMMENT '更新时间', is_deleted tinyint(2) DEFAULT 0 COMMENT '是否逻辑删除' ) ENGINE = InnoDB CHARACTER SET = utf8 COMMENT = '用户收货地址'; ``` -------------------------------- ### Console Log Output Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/many2many_demo Example of the SQL logs generated when accessing the associated entity list. ```text DEBUG - ==> Preparing: SELECT id, ..., user_name FROM t_member WHERE id = ? DEBUG - ==> Parameters: 1(Long) DEBUG - <== Total: 1 DEBUG - ==> Preparing: SELECT id, ..., member_id FROM t_member_favorite WHERE member_id = ? DEBUG - ==> Parameters: 1(Long) DEBUG - <== Total: 2 爱好项: 2 ``` -------------------------------- ### Console Log Output for Default Values Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/02-advanced-hello-world Example of the generated SQL and object output showing default values applied. ```text Preparing: INSERT INTO hello_world(say_hello, your_name, gmt_create, gmt_modified, is_deleted) VALUES (?, ?, now(), now(), 0) 2517 [main] DEBUG c.o.a.f.m.d.e.m.H.insert - ==> Parameters: hello(String), fluent mybatis(String) 2518 [main] DEBUG c.o.a.f.m.d.e.m.H.insert - <== Updates: 1 HelloWorldEntity(id=7, sayHello=hello, yourName=fluent mybatis, gmtCreate=Fri Oct 09 22:35:06 CST 2020, gmtModified=Fri Oct 09 22:35:06 CST 2020, isDeleted=false) ``` -------------------------------- ### HTTPS Authentication Prompt Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop Example of the authentication prompt encountered when using HTTPS; use a personal access token instead of a password. ```text Username for 'https://gitee.com': userName Password for 'https://userName@gitee.com': # Private Token ``` -------------------------------- ### Importing a BaseDao class Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/issues/I4C49U Example of an import statement for a generated BaseDao class that may be missing if the code generation process was not executed correctly. ```java import cn.org.fluent.mybatis.springboot.demo.dao.base.CountyDivisionBaseDao; ``` -------------------------------- ### Debug Log Output for One-to-Many Query Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/many2many_demo Example of the SQL generated by Fluent Mybatis when executing the conditional query. ```text DEBUG - ==> Preparing: SELECT id, ..., user_name FROM t_member WHERE id = ? DEBUG - ==> Parameters: 1(Long) DEBUG - <== Total: 1 DEBUG - ==> Preparing: SELECT id, ..., member_id FROM t_member_favorite WHERE is_deleted = ? AND member_id = ? DEBUG - ==> Parameters: false(Boolean), 1(Long) DEBUG - <== Total: 2 爱好项: 2 ``` -------------------------------- ### Create Database Table Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/spring-boot-demo SQL script to create the sample table used for demonstration. ```sql DROP TABLE IF EXISTS `your_table`; create table `your_table` ( id bigint auto_increment comment '主键ID' primary key, name varchar(30) charset utf8 null comment '姓名', age int null comment '年龄', email varchar(50) charset utf8 null comment '邮箱', gmt_create datetime null comment '记录创建时间', gmt_modified datetime null comment '记录最后修改时间', is_deleted tinyint(2) default 0 null comment '逻辑删除标识' ); ``` -------------------------------- ### Define Database Schema Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/01-hello-world Create the hello_world table structure required for the demonstration. ```sql create schema fluent_mybatis; create table hello_world ( id bigint unsigned auto_increment primary key, say_hello varchar(100) null, your_name varchar(100) null, gmt_created datetime DEFAULT NULL COMMENT '创建时间', gmt_modified datetime DEFAULT NULL COMMENT '更新时间', is_deleted tinyint(2) DEFAULT 0 COMMENT '是否逻辑删除' ) ENGINE = InnoDB CHARACTER SET = utf8 comment '简单演示表'; ``` -------------------------------- ### Initialize Student Database Table Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/fluent-mybatis-dynamic SQL script to create the student table with standard audit fields. ```sql DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `id` bigint(21) unsigned NOT NULL AUTO_INCREMENT COMMENT '编号', `name` varchar(20) DEFAULT NULL COMMENT '姓名', `phone` varchar(20) DEFAULT NULL COMMENT '电话', `email` varchar(50) DEFAULT NULL COMMENT '邮箱', `gender` tinyint(2) DEFAULT NULL COMMENT '性别', `locked` tinyint(2) DEFAULT NULL COMMENT '状态(0:正常,1:锁定)', `gmt_created` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '存入数据库的时间', `gmt_modified` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改的时间', `is_deleted` tinyint(2) DEFAULT 0, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT ='学生表'; ``` -------------------------------- ### Generated Entity Class Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/spring-boot-demo Example of an entity class generated by Fluent MyBatis with appropriate annotations. ```java @Data @Accessors(chain = true) @FluentMybatis(table = "your_table") public class YourEntity implements IEntity{ private static final long serialVersionUID = 1L; @TableId(value = "id") private Long id; @TableField(value = "gmt_create", insert = "now()") private Date gmtCreate; @TableField(value = "gmt_modified", insert = "now()", update = "now()") private Date gmtModified; @TableField(value = "is_deleted", insert = "0") private Boolean isDeleted; @TableField(value = "age") private Integer age; @TableField(value = "email") private String email; @TableField(value = "name") private String name; @Override public Serializable findPk() { return id; } } ``` -------------------------------- ### 新增数据并自动填充环境和租户 Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/env_tenant_demo 演示插入数据时,即使未显式设置 env 和 tenant 属性,系统也会自动填充这些字段。 ```java @RunWith(SpringRunner.class) @SpringBootTest(classes = AppMain.class) public class InsertWithEnvDemo { @Autowired private StudentMapper mapper; @Test public void insertEntity() { mapper.delete(new StudentQuery()); mapper.insert(new StudentEntity() .setAddress("宇宙深处") .setUserName("FluentMybatis") ); StudentEntity student = mapper.findOne(StudentQuery.query() .where.userName().eq("FluentMybatis").end() .limit(1)); System.out.println(student.getUserName() + ", env:" + student.getEnv() + ", tenant:" + student.getTenant()); } } ``` ```text DEBUG - ==> Preparing: INSERT INTO student(gmt_created, gmt_modified, is_deleted, address, env, tenant, user_name) VALUES (now(), now(), 0, ?, ?, ?, ?) DEBUG - ==> Parameters: 宇宙深处(String), test1(String), 222222(Long), FluentMybatis(String) DEBUG - <== Updates: 1 DEBUG - ==> Preparing: SELECT id, gmt_created, gmt_modified, is_deleted, address, age, birthday, bonus_points, env, gender_man, grade, home_address_id, home_county_id, phone, status, tenant, user_name, version FROM student WHERE user_name = ? LIMIT ?, ? DEBUG - ==> Parameters: FluentMybatis(String), 0(Integer), 1(Integer) DEBUG - <== Total: 1 FluentMybatis, env:test1, tenant:222222 ``` -------------------------------- ### MyBatis XML Multi-Update Statement Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/issues/I3IPR5 Example of a MyBatis XML mapper configuration for executing multiple update statements in one call. ```xml UPDATE a_foo set password = #{password} WHERE a_id = #{id, jdbcType=INTEGER}; UPDATE b_foo set password = #{password} WHERE b_id = #{id, jdbcType=INTEGER}; ``` -------------------------------- ### Configure Annotation Processors in 01-hello-world/pom.xml Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/pulls/1.patch Updates the compiler plugin configuration to include annotationProcessorPaths for Lombok and fluent-mybatis-processor. ```xml --- a/01-hello-world/pom.xml +++ b/01-hello-world/pom.xml @@ -11,6 +11,7 @@ 1.8.0.1 5.3.3 + 1.18.20 @@ -18,20 +19,8 @@ fluent-mybatis ${fluent.mybatis.version} - - com.github.atool - fluent-mybatis-processor - ${fluent.mybatis.version} - provided - - - org.projectlombok - lombok - 1.18.20 - provided - mysql mysql-connector-java @@ -82,6 +71,18 @@ 1.8 1.8 utf-8 + + + org.projectlombok + lombok + ${org.projectlombok.version} + + + com.github.atool + fluent-mybatis-processor + ${fluent.mybatis.version} + + ``` -------------------------------- ### SQL Query with Reserved Keyword Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/issues/I4758K Example of a SQL query where 'Index' is used as a column name, requiring special handling due to it being a reserved keyword. ```sql SELECT * FROM Test WHERE [Index] >= 1 ``` -------------------------------- ### Configure Spring Beans Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/01-hello-world Set up the Spring configuration class including DataSource, SqlSessionFactoryBean, and MapperFactory. ```java @ComponentScan(basePackages = "cn.org.atool.fluent.mybatis.demo1") @MapperScan("cn.org.atool.fluent.mybatis.demo1.entity.mapper") @Configuration public class HelloWorldConfig { /** * 设置dataSource属性 * * @return */ @Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/fluent_mybatis?useUnicode=true&characterEncoding=utf8"); dataSource.setUsername("root"); dataSource.setPassword("password"); return dataSource; } /** * 定义mybatis的SqlSessionFactoryBean * * @param dataSource * @return */ @Bean public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean; } @Bean public MapperFactory mapperFactory() { return new MapperFactory(); } } ``` -------------------------------- ### Incorrect Oracle SQL Output Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/issues/I43972 Example of the generated SQL containing double quotes around column names, which causes syntax errors in Oracle. ```sql INSERT INTO T_MESSAGES ("phone_num", "type", "code", "status", "msg") VALUES ('*****', 1, 'test', false, 'test') ``` -------------------------------- ### Build commands for code generation Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/issues/I1Z2CX Use these commands to trigger the compilation process and generate the required classes. ```bash mvn compile ``` ```bash gradle build ``` -------------------------------- ### Scan projects with OpenSCA CLI Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/open_sca Use the CLI tool to analyze project dependencies and vulnerabilities with various output and configuration options. ```bash opensca-cli -path ${project_path} ``` ```bash opensca-cli -path ${project_path} -out report.html ``` ```bash opensca-cli -url ${url} -token ${token} -path ${project_path} ``` ```bash opensca-cli -db db.json -path ${project_path} ``` -------------------------------- ### 实现IDefaultSetter进行自动拦截 Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/env_tenant_demo 通过实现IDefaultSetter接口,在增删改查操作中自动注入环境和租户条件。 ```java /** * 增删改查中,环境和租户隔离设置 */ public interface IsolateSetter extends IDefaultSetter { /** * 插入的entity,如果没有显式设置环境和租户,根据工具类进行默认设置 * * @param entity */ @Override default void setInsertDefault(IEntity entity) { IsolateEntity isolateEntity = (IsolateEntity) entity; if (isolateEntity.getEnv() == null) { isolateEntity.setEnv(EnvUtils.currEnv()); } if (isolateEntity.getTenant() == null) { isolateEntity.setTenant(TenantUtils.findUserTenant()); } } /** * 查询条件追加环境隔离和租户隔离 * * @param query */ @Override default void setQueryDefault(IQuery query) { query.where() .apply("env", SqlOp.EQ, EnvUtils.currEnv()) .apply("tenant", SqlOp.EQ, TenantUtils.findUserTenant()); } /** * 更新条件追加环境隔离和租户隔离 * * @param updater */ @Override default void setUpdateDefault(IUpdate updater) { updater.where() .apply("env", SqlOp.EQ, EnvUtils.currEnv()) .apply("tenant", SqlOp.EQ, TenantUtils.findUserTenant()); } } ``` -------------------------------- ### Configure Spring Beans Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/v1.5/01-hello-world Set up the DataSource and SqlSessionFactoryBean for the Fluent Mybatis application using Spring configuration. ```java @ComponentScan(basePackages = "cn.org.atool.fluent.mybatis.demo1") @MapperScan("cn.org.atool.fluent.mybatis.demo1.entity.mapper") @Configuration public class HelloWorldConfig { /** * 设置dataSource属性 * * @return */ @Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/fluent_mybatis_tutorial?useUnicode=true&characterEncoding=utf8"); dataSource.setUsername("root"); dataSource.setPassword("password"); return dataSource; } /** * 定义mybatis的SqlSessionFactoryBean * * @param dataSource * @return */ @Bean public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean; } } ``` -------------------------------- ### Create Entity Class Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/01-hello-world Define the HelloWorldEntity class annotated with @FluentMybatis and extending RichEntity. ```java @FluentMybatis public class HelloWorldEntity extends RichEntity { private Long id; private String sayHello; private String yourName; private Date gmtCreated; private Date gmtModified; private Boolean isDeleted; // get, set, toString 方法 @Override public Class entityClass() { return HelloWorldEntity.class; } } ``` -------------------------------- ### Configure Maven Dependencies Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/01-hello-world Include the fluent-mybatis runtime and processor dependencies in your pom.xml file. ```xml com.github.atool fluent-mybatis 1.9.7 com.github.atool fluent-mybatis-processor 1.9.7 ``` -------------------------------- ### Configure and execute EntityGenerator Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/v1.5/03-entity-generator Use the EntityGenerator class to define output paths, package names, database credentials, and the tables to be processed. ```java public class EntityGeneratorDemo { public static void main(String[] args) throws Exception { EntityGenerator.build() .globalConfig(g -> g /** 设置src/java 所在的路径 **/ .setOutputDir(baseDir + "src/main/java/") /** 设置package **/ .setBasePackage("cn.org.atool.fluent.mybatis.demo3") /** 设置数据库连接 **/ .setDataSource(url, "root", "password") ) .tables(t -> t /** 设置需要生成Entity类的表 **/ .table("hello_world") //.table("其它表") //.table("其它表") ) .execute(); } } ``` -------------------------------- ### 使用默认条件查询数据 Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/env_tenant_demo 演示使用 defaultQuery() 方法,该方法会自动应用 IsolateSetter 中定义的默认查询条件。 ```java @RunWith(SpringRunner.class) @SpringBootTest(classes = AppMain.class) public class QueryWithEnvDemo { @Autowired private StudentMapper mapper; @Test public void testQueryWithEnv(){ mapper.delete(new StudentQuery()); mapper.insert(new StudentEntity() .setAddress("宇宙深处") .setUserName("FluentMybatis") ); StudentEntity student = mapper.findOne(mapper.defaultQuery() .where.userName().eq("FluentMybatis").end() .limit(1)); System.out.println(student.getUserName() + ", env:" + student.getEnv() + ", tenant:" + student.getTenant()); } } ``` ```text DEBUG - ==> Preparing: SELECT id, gmt_created, ... , tenant, user_name, version FROM student WHERE env = ? AND tenant = ? AND user_name = ? LIMIT ?, ? DEBUG - ==> Parameters: test1(String), 222222(Long), FluentMybatis(String), 0(Integer), 1(Integer) DEBUG - <== Total: 1 FluentMybatis, env:test1, tenant:222222 ``` -------------------------------- ### Implement Choose Logic in MyBatis XML Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/fluent-mybatis-dynamic Standard MyBatis XML configuration using , , and tags to handle conditional query logic. ```xml ``` -------------------------------- ### Maven Compiler Annotation Processor Configuration Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/pulls/1/checks Recommendation to configure annotation processors via the maven-compiler plugin instead of adding them as direct dependencies. ```text 应该使用 maven-compiler 指定注解处理器,而不是引入依赖的方式 ``` -------------------------------- ### 查看FluentMybatis注解定义 Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/env_tenant_demo FluentMybatis注解中用于配置默认设置实现的属性。 ```java public @interface FluentMybatis { /** * entity, query, updater默认值设置实现 * * @return */ Class defaults() default IDefaultSetter.class; } ``` -------------------------------- ### SQL for Many-to-Many Queries Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/master/many2many_demo SQL queries for fetching ex-partners based on gender and relationship status. ```sql select * from t_member where is_deleted=0 and id in (select boy_id from t_memeber_love where status = '前任' and girl_id = ? -- 女孩id and is_deleted = 0 ) ``` ```sql select * from t_member where is_deleted=0 and id in (select girl_id from t_memeber_love where status = '前任' and boy_id= ? -- 男孩id and is_deleted = 0 ) ``` -------------------------------- ### 配置 FluentMybatis 代码生成器 Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/many2many_demo 使用 @Tables 注解配置数据库连接信息及表映射,通过 FileGenerator.build 方法生成对应的 Entity 类。 ```java public class AppEntityGenerator { static final String url = "jdbc:mysql://localhost:3306/fluent_mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8"; /** * 生成代码的package路径 */ static final String basePackage = "cn.org.fluent.mybatis.many2many.demo"; public static void main(String[] args) { FileGenerator.build(Noting.class); } @Tables( /** 数据库连接信息 **/ url = url, username = "root", password = "password", /** Entity类parent package路径 **/ basePack = basePackage, /** Entity代码源目录 **/ srcDir = "example/many2many_demo/src/main/java", /** 如果表定义记录创建,记录修改,逻辑删除字段 **/ gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted", /** 需要生成文件的表 ( 表名称:对应的Entity名称 ) **/ tables = @Table(value = {"t_member", "t_member_love", "t_member_favorite"}, tablePrefix = "t_") ) static class Noting { } } ``` -------------------------------- ### Configure Full Entity Code Generation Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/many2many_demo Defines the database connection, package structure, and relationship mappings for automatic Entity generation. ```java public class AppEntityFullGenerator { static final String url = "jdbc:mysql://localhost:3306/fluent_mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8"; /** * 生成代码的package路径 */ static final String basePackage = "cn.org.fluent.mybatis.many2many.demo"; public static void main(String[] args) { FileGenerator.build(Noting.class); } @Tables( /** 数据库连接信息 **/ url = url, username = "root", password = "password", /** Entity类parent package路径 **/ basePack = basePackage, /** Entity代码源目录 **/ srcDir = "example/many2many_demo/src/main/java", /** 如果表定义记录创建,记录修改,逻辑删除字段 **/ gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted", /** 需要生成文件的表 ( 表名称:对应的Entity名称 ) **/ tables = @Table(value = {"t_member", "t_member_love", "t_member_favorite"}, tablePrefix = "t_"), relations = { @Relation(method = "findMyFavorite", source = "t_member", target = "t_member_favorite", type = RelationType.OneWay_0_N , where = "id=member_id && is_deleted=is_deleted"), @Relation(method = "findExFriends", source = "t_member", target = "t_member", type = RelationType.OneWay_0_N), @Relation(method = "findCurrFriend", source = "t_member", target = "t_member", type = RelationType.OneWay_0_1) } ) static class Noting { } } ``` -------------------------------- ### Create student table with isolation fields Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/env_tenant_demo Defines the student table schema including 'env' for environment isolation and 'tenant' for multi-tenant data separation. ```sql create table student ( id bigint(21) unsigned auto_increment comment '主键id' primary key, age int null comment '年龄', grade int null comment '年级', user_name varchar(45) null comment '名字', gender_man tinyint(2) default 0 null comment '性别, 0:女; 1:男', birthday datetime null comment '生日', phone varchar(20) null comment '电话', bonus_points bigint(21) default 0 null comment '积分', status varchar(32) null comment '状态(字典)', home_county_id bigint(21) null comment '家庭所在区县', home_address_id bigint(21) null comment 'home_address外键', address varchar(200) null comment '家庭详细住址', version varchar(200) null comment '版本号', env varchar(10) NULL comment '数据隔离环境', tenant bigint NOT NULL default 0 comment '租户标识', gmt_created datetime null comment '创建时间', gmt_modified datetime null comment '更新时间', is_deleted tinyint(2) default 0 null comment '是否逻辑删除' ) ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT '学生信息表'; ``` -------------------------------- ### Test4J Configuration Properties Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/04-advanced-generator Configuration file for Test4J database connectivity, placed in src/test/resources. ```properties db.dataSource.list=dataSource db.dataSource.script.factory=cn.org.atool.fluent.mybatis.tutorial.DataSourceScript db.dataSource.type=mysql db.dataSource.driver=com.mysql.jdbc.Driver db.dataSource.url=jdbc:mysql://localhost:3306/fluent_mybatis?characterEncoding=utf8 db.dataSource.userName=root db.dataSource.password=password db.dataSource.schemaName=fluent_mybatis ``` -------------------------------- ### SQL for Querying Ex-Boyfriends Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/many2many_demo SQL logic required when the member is female. ```sql select * from t_member where is_deleted=0 and id in (select girl_id from t_memeber_love where status = '前任' and boy_id= ? -- 男孩id and is_deleted = 0 ) ``` -------------------------------- ### SQL for Querying Ex-Girlfriends Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/many2many_demo SQL logic required when the member is male. ```sql select * from t_member where is_deleted=0 and id in (select boy_id from t_memeber_love where status = '前任' and girl_id = ? -- 女孩id and is_deleted = 0 ) ``` -------------------------------- ### Debug Log Output for Many-to-Many Query Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/many2many_demo Log output showing the dynamic SQL generation for the many-to-many relationship. ```text DEBUG - ==> Preparing: SELECT id, ..., user_name FROM t_member WHERE id = ? DEBUG - ==> Parameters: 1(Long) DEBUG - <== Total: 1 是否女孩:true DEBUG - ==> Preparing: SELECT id, ..., user_name FROM t_member WHERE is_deleted = ? AND id IN (SELECT boy_id FROM t_member_love WHERE status = ? AND is_deleted = ? AND girl_id = ?) DEBUG - ==> Parameters: false(Boolean), 前任(String), false(Boolean), 1(Long) DEBUG - <== Total: 1 [MemberEntity(id=2, gmtModified=Sun Nov 08 12:31:57 CST 2020, isDeleted=false, age=null, gmtCreated=null, isGirl=false, school=null, userName=mike)] ``` -------------------------------- ### 定义多对多关系数据库表结构 Source: https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/develop/many2many_demo 包含成员表、恋爱关系表以及成员爱好表的 SQL 定义,用于支持多对多关联查询。 ```sql CREATE TABLE t_member ( id bigint(21) unsigned auto_increment primary key COMMENT '主键id', user_name varchar(45) DEFAULT NULL COMMENT '名字', is_girl tinyint(1) DEFAULT 0 COMMENT '0:男孩; 1:女孩', age int DEFAULT NULL COMMENT '年龄', school varchar(20) DEFAULT NULL COMMENT '学校', gmt_created datetime DEFAULT NULL COMMENT '创建时间', gmt_modified datetime DEFAULT NULL COMMENT '更新时间', is_deleted tinyint(1) DEFAULT 0 COMMENT '是否逻辑删除' ) ENGINE = InnoDB CHARACTER SET = utf8 COMMENT = '成员表:女孩或男孩信息'; CREATE TABLE t_member_love ( id bigint(21) unsigned auto_increment primary key COMMENT '主键id', girl_id bigint(21) NOT NULL COMMENT 'member表外键', boy_id bigint(21) NOT NULL COMMENT 'member表外键', status varchar(45) DEFAULT NULL COMMENT '状态', gmt_created datetime DEFAULT NULL COMMENT '创建时间', gmt_modified datetime DEFAULT NULL COMMENT '更新时间', is_deleted tinyint(2) DEFAULT 0 COMMENT '是否逻辑删除' ) ENGINE = InnoDB CHARACTER SET = utf8 COMMENT = '成员恋爱关系'; CREATE TABLE t_member_favorite ( id bigint(21) unsigned auto_increment primary key COMMENT '主键id', member_id bigint(21) NOT NULL COMMENT 'member表外键', favorite varchar(45) DEFAULT NULL COMMENT '爱好: 电影, 爬山, 徒步...', gmt_created datetime DEFAULT NULL COMMENT '创建时间', gmt_modified datetime DEFAULT NULL COMMENT '更新时间', is_deleted tinyint(2) DEFAULT 0 COMMENT '是否逻辑删除' ) ENGINE = InnoDB CHARACTER SET = utf8 COMMENT = '成员爱好'; ```