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 '逻辑删除标识'
);
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.url=jdbc:mysql://localhost:3306/fluent_mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
public class AppEntityGenerator {static final String url = "jdbc:mysql://localhost:3306/fluent_mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8";public static void main(String[] args) {FileGenerator.build(Abc.class);}@Tables(/** 数据库连接信息 **/url = url, username = "root", password = "password",/** Entity类parent package路径 **/basePack = "cn.org.fluent.mybatis.springboot.demo",/** Entity代码源目录 **/srcDir = "spring-boot-demo/src/main/java",/** Dao代码源目录 **/daoDir = "spring-boot-demo/src/main/java",/** 如果表定义记录创建,记录修改,逻辑删除字段 **/gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted",/** 需要生成文件的表 **/tables = @Table(value = {"your_table"}))static class Abc {}
}
@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;@Overridepublic Serializable findPk() {return id;}
}
@Repository
public class YourDaoImpl extends YourBaseDao implements YourDao {// 在这里添加你自己的业务逻辑代码
}
@SpringBootTest(classes = QuickStartApplication.class)
public class FluentMybatisApplicationTest {&#64;Autowiredprivate YourMapper yourMapper;&#64;Testvoid contextLoads() {List<YourEntity> list &#61; yourMapper.listEntity(yourMapper.query());for (YourEntity entity : list) {System.out.println(entity);}}
}
EntityMapper提供的insert操作
insert->单条插入操作->Mapper方法
public interface YourMapper extends IEntityMapper<YourEntity> {/**1. 插入一条记录2. 3. &#64;param entity4. &#64;return*/&#64;Override&#64;InsertProvider(type &#61; YourSqlProvider.class,method &#61; "insert")&#64;Options(useGeneratedKeys &#61; true,keyProperty &#61; "id",keyColumn &#61; "id")int insert(YourEntity entity);
}
public class YourSqlProvider {public String insert(YourEntity entity) {assertNotNull("entity", entity);MapperSql sql &#61; new MapperSql();sql.INSERT_INTO("your_table");List<String> columns &#61; new ArrayList<>();List<String> values &#61; new ArrayList<>();if (entity.getId() !&#61; null) {columns.add("id");values.add("#{id}");}columns.add("gmt_create");if (entity.getGmtCreate() !&#61; null) {values.add("#{gmtCreate}");} else {values.add("now()");}columns.add("gmt_modified");if (entity.getGmtModified() !&#61; null) {values.add("#{gmtModified}");} else {values.add("now()");}columns.add("is_deleted");if (entity.getIsDeleted() !&#61; null) {values.add("#{isDeleted}");} else {values.add("0");}if (entity.getAge() !&#61; null) {columns.add("age");values.add("#{age}");}if (entity.getEmail() !&#61; null) {columns.add("email");values.add("#{email}");}if (entity.getName() !&#61; null) {columns.add("name");values.add("#{name}");}sql.INSERT_COLUMNS(columns);sql.VALUES();sql.INSERT_VALUES(values);return sql.toString();}
}
DEBUG - &#61;&#61;> Preparing: INSERT INTO your_table(gmt_create, gmt_modified, is_deleted, age, email, name) VALUES (now(), now(), ?, ?, ?, ?)
DEBUG - &#61;&#61;> Parameters: false(Boolean), 1(Integer), darui.wu&#64;163.com(String), Fluent Mybatis(String)
DEBUG - <&#61;&#61; Updates: 1
count:1
entity:YourEntity(id&#61;18, gmtCreate&#61;null, gmtModified&#61;null, isDeleted&#61;false, age&#61;1, email&#61;darui.wu&#64;163.com, name&#61;Fluent Mybatis)
注意:
&#64;Options(useGeneratedKeys &#61; true,keyProperty &#61; "id",keyColumn &#61; "id"
)
&#64;TableField(value &#61; "gmt_create", insert &#61; "now()")private Date gmtCreate;&#64;TableField(value &#61; "gmt_modified", insert &#61; "now()", update &#61; "now()")private Date gmtModified;&#64;TableField(value &#61; "is_deleted", insert &#61; "0")private Boolean isDeleted;
INSERT INTO your_table
(gmt_create, gmt_modified, is_deleted, age, email, name)
VALUES
(now(), now(), ?, ?, ?, ?)
public class YourSqlProvider {public String insert(YourEntity entity) {List<String> columns &#61; new ArrayList<>();List<String> values &#61; new ArrayList<>();// 省略 ... ...columns.add("gmt_create");if (entity.getGmtCreate() !&#61; null) {values.add("#{gmtCreate}");} else {values.add("now()");}columns.add("gmt_modified");if (entity.getGmtModified() !&#61; null) {values.add("#{gmtModified}");} else {values.add("now()");}columns.add("is_deleted");if (entity.getIsDeleted() !&#61; null) {values.add("#{isDeleted}");} else {values.add("0");}if (entity.getAge() !&#61; null) {columns.add("age");values.add("#{age}");}// 省略... ...return sql.toString();}
}
public class YourSqlProvider {public String insertBatch(Map map) {assertNotEmpty("map", map);MapperSql sql &#61; new MapperSql();List<YourEntity> entities &#61; getParas(map, "list");sql.INSERT_INTO("your_table");sql.INSERT_COLUMNS(ALL_ENTITY_FIELDS);sql.VALUES();for (int index &#61; 0; index < entities.size(); index&#43;&#43;) {if (index > 0) {sql.APPEND(", ");}sql.INSERT_VALUES("#{list[" &#43; index &#43; "].id}",entities.get(index).getGmtCreate() &#61;&#61; null ? "now()" : "#{list[" &#43; index &#43; "].gmtCreate}",entities.get(index).getGmtModified() &#61;&#61; null ? "now()" : "#{list[" &#43; index &#43; "].gmtModified}",entities.get(index).getIsDeleted() &#61;&#61; null ? "0" : "#{list[" &#43; index &#43; "].isDeleted}","#{list[" &#43; index &#43; "].age}","#{list[" &#43; index &#43; "].email}","#{list[" &#43; index &#43; "].name}");}return sql.toString();}
}
SQL构造语句是通过一个for循环遍历实体列表&#xff0c;构造出下列SQL语句, 其中对有insert默认值属性处理方式同单条insert一样, 这里就不再重复。
NSERT INTO your_table (&#39;Entity对应的字段列表&#39;) VALUES (&#39;实例1值&#39;), (&#39;实例2值&#39;)
写个测试看看具体效果
&#64;SpringBootTest(classes &#61; QuickStartApplication.class)
public class FluentMybatisApplicationTest {&#64;Autowiredprivate YourMapper yourMapper;void insertBatch(){List<YourEntity> entities &#61; new ArrayList<>();entities.add(new YourEntity().setName("Fluent Mybatis").setEmail("darui.wu&#64;163.com"));entities.add(new YourEntity().setName("Fluent Mybatis Demo").setEmail("darui.wu&#64;163.com"));entities.add(new YourEntity().setName("Test4J").setEmail("darui.wu&#64;163.com"));int count &#61; yourMapper.insertBatch(entities);System.out.println("count:" &#43; count);System.out.println("entity:" &#43; entities);}
}
执行测试&#xff0c;查看控制台输出
DEBUG - &#61;&#61;> Preparing: INSERT INTO your_table(id, gmt_create, gmt_modified, is_deleted, age, email, name) VALUES (?, now(), now(), 0, ?, ?, ?) , (?, now(), now(), 0, ?, ?, ?) , (?, now(), now(), 0, ?, ?, ?)
DEBUG - &#61;&#61;> Parameters: null, null, darui.wu&#64;163.com(String), Fluent Mybatis(String), null, null, darui.wu&#64;163.com(String), Fluent Mybatis Demo(String), null, null, darui.wu&#64;163.com(String), Test4J(String)
DEBUG - <&#61;&#61; Updates: 3
count:3
entity:[YourEntity(id&#61;null, gmtCreate&#61;null, gmtModified&#61;null, isDeleted&#61;null, age&#61;null, email&#61;darui.wu&#64;163.com, name&#61;Fluent Mybatis), YourEntity(id&#61;null, gmtCreate&#61;null, gmtModified&#61;null, isDeleted&#61;null, age&#61;null, email&#61;darui.wu&#64;163.com, name&#61;Fluent Mybatis Demo), YourEntity(id&#61;null, gmtCreate&#61;null, gmtModified&#61;null, isDeleted&#61;null, age&#61;null, email&#61;darui.wu&#64;163.com, name&#61;Test4J)]