mybatis 自定义自动增长设置

本文介绍如何在MyBatis中通过后台配置SQL实现主键自定义自动增长。通过分析mybatis的执行链,理解KeyGenerator接口及其三个子类的作用,特别是Jdbc3KeyGenerator和SelectKeyGenerator。项目需求是在实体类上配置,使得插入操作时能够处理自动增长。文章提出了利用MyBatis拦截器拦截update方法,通过实体类注解和MappedStatement的keyGenerator属性设置,实现在程序中设置自动增长功能。
摘要由CSDN通过智能技术生成

项目需求:将mybats用后台的方式配置sql,在定义表对应的实体时,自定义设置主键自动增长。

mybaits 插入SQL源码分析执行链:BaseExecutor(update) --> SimpleExecutor(doUpdate)-->SimpleStatementExecutor(update),

@Override
  public int update(Statement statement) throws SQLException {
    String sql = boundSql.getSql();
    Object parameterObject = boundSql.getParameterObject();
    KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();
    int rows;
    if (keyGenerator instanceof Jdbc3KeyGenerator) {
      statement.execute(sql, Statement.RETURN_GENERATED_KEYS);
      rows = statement.getUpdateCount();
      keyGenerator.processAfter(executor, mappedStatement, statement, parameterObject);
    } else if (keyGenerator instanceof SelectKeyGenerator) {
      statement.execute(sql);
      rows = statement.getUpdateCount();
      keyGenerator.processAfter(executor, mappedStatement, statement, parameterObject);
    } else {
    
在使用MyBatis操作Oracle数据库时,Oracle默认的自增长字段是通过序列(Sequence)实现的。要在自定义表中实现自增,可以通过以下步骤实现: 1. 创建一个序列: 在Oracle数据库中,可以使用CREATE SEQUENCE语句创建一个序列。例如创建一个名为custom_table_seq的序列,步长为1,起始值为1: ``` CREATE SEQUENCE custom_table_seq START WITH 1 INCREMENT BY 1; ``` 2. 在自定义表中添加一个数值类型的字段作为自增字段: 在自定义表中添加一个名为id的数值类型字段,用来保存自增的值。 ``` ALTER TABLE custom_table ADD id NUMBER(10); ``` 3. 在MyBatis的Mapper XML文件中配置插入语句: 在Mapper XML文件中,可以使用SELECT LAST_INSERT_ID()函数获得自增的值,并将其插入到自定义表的id字段中。 ``` <insert id="insertCustomTable" parameterType="CustomTable"> <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.Long"> SELECT custom_table_seq.NEXTVAL FROM DUAL </selectKey> INSERT INTO custom_table (id, column1, column2) VALUES (#{id}, #{column1}, #{column2}) </insert> ``` 上述代码中,selectKey标签用于获取序列的下一个值,并将其设置到id属性上。 需要注意的是,在使用Generator类生成的实体类中,需要添加相应的属性和getter、setter方法。同时,还需要在DAO接口中定义插入方法。 ``` public void insertCustomTable(CustomTable customTable); ``` 通过以上步骤,便可以在自定义表中实现自增功能。每次插入数据时,自定义表的id字段都会自动增加,并保持唯一。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值