前言
今天介绍一下myabtisGenerator项目。以及如何使用逆向工程
准备工作
准备创建一张订单表,建表语句如下
CREATE TABLE `common_order` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id',
`order_no` varchar(50) NOT NULL DEFAULT '0' COMMENT '订单号',
`order_type` smallint(6) unsigned NOT NULL DEFAULT '0' COMMENT '订单类型',
`buyer_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '买家id',
`buyer_name` varchar(45) NOT NULL DEFAULT '0' COMMENT '买家名',
`seller_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '卖家id',
`seller_name` varchar(45) NOT NULL DEFAULT '0' COMMENT '卖家名',
`status` TINYINT(6) unsigned NOT NULL DEFAULT '0' COMMENT '订单状态',
`origin_price` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '订单原价',
`real_price` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '订单实付价',
`succeed_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '订单成功时间',
`delete_flag` tinyint(4) unsigned NOT NULL DEFAULT '0' COMMENT '是否删除',
`version` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '版本号',
`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '编辑时间',
`last_editor` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '最后编辑者',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='交易订单表'
优化
其实进行了3个地方的优化
- 生成对应的注释。在获得数据库中字段的数据时,把注释也在java文件中写出来,
- smallInt,tinyint不适用java的Short类型而使用Integer
- 时间类型转变为LocalDateTime
如何使用逆向工程
public class test {
@Resource
private CommonOrderMapper commonOrderMapper;
public void test(){
//简单select 方法
//select * from common_order where order_no = "111"
CommonOrder commonOrder = new CommonOrder();
CommonOrderExample example = new CommonOrderExample();
CommonOrderExample.Criteria criteria = example.createCriteria();
criteria.andOrderNoEqualTo("111");
commonOrderMapper.selectByExample(example);
//这个criteria还有例如!=, =, >=, <=, in, not in 等等这些api方法可以使用
//or 条件方法
//select * from common_order where order_no = "111" or id = 1
CommonOrderExample.Criteria criteria2 = example.createCriteria();
criteria2.andBuyerIdEqualTo(1L);
example.or(criteria2);
commonOrderMapper.selectByExample(example);
//insert方法
commonOrderMapper.insertSelective(commonOrder);
//update方法
commonOrderMapper.updateByExampleSelective(commonOrder,example);
//delete方法
commonOrderMapper.deleteByExample(example);
}
}
小tips:
mybatis如何返回insert的主键
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert语句
</insert>
useGeneratedKeys 设置为true后,MyBatis 会使用 JDBC的getGeneratedKeys 方法来取出由数据库内部生成的主键。获取主键值后将其赋值给 keyProperty 配置的 id 属性。
最后,逆向工程java项目下载
https://github.com/alex9567/mybatisGeneral