简体   繁体   中英

How to populate object property with value generated by Mysql Trigger in MyBatis Insert

I can't get the value back from function. It does an insert on a table and must return a number. The data is insert correctly, but the number returned is always null.

Mysql

create table driver_order (
  id int(11) unsigned NOT NULL AUTO_INCREMENT,
  area_start varchar(200),
  area_end varchar(200),
  order_number varchar(200),
  create_user varchar(200),
  primary key (id)
);

DELIMITER $$
CREATE TRIGGER seq_driver_order_number BEFORE INSERT ON driver_order
FOR each ROW
BEGIN
    DECLARE seq_type INT(10);
    SET seq_type = getUserNo(NEW.create_user);
    SET NEW.order_number = getNextCommSequence("motor", seq_type);
END$$
DELIMITER ;

Mybatis

<insert id="insertOrder" useGeneratedKeys="true" keyProperty="id" parameterType="DriverOrder">
    INSERT INTO 
    DRIVER_ORDER(ID,ORDER_NUMBER,AREA_START,AREA_END,CREATE_USER,CREATE_TIME) 
    VALUES
      (#{id},
       #{orderNumber,jdbcType=VARCHAR},
       #{areaStart,jdbcType=VARCHAR},
       #{areaEnd,jdbcType=VARCHAR},
       #{createUser,jdbcType=VARCHAR},
       now())
</insert>

The return Object all attributes have correctly value include id, except order_number which TRIGGER set value is return null. Is there something wrong?

The problem is not with a trigger but how to make mybatis get value generated on mysql side during record insertion. Mybatis is rather simple tool in sense that you can't specify properties to columns mapping and everything else happens automagically.

Mybatis core is sql queries not properties-to-columns mappings like in hibernate for example. So mybatis only executes queries and simplifies setting parameters and construction objects from query result.

Nevertheless starting from version 3.2.6 you can use selectKey to get several values and set properties in the object being inserted. If you combine this with last_insert_id() you can get what you need. For your case it is done like this:

<insert id="insertOrder" parameterType="DriverOrder">
  <selectKey keyProperty="id,orderNumber" keyColumn="ID,ORDER_NUMBER" order="AFTER" resultType="java.util.Map">
    SELECT ID,ORDER_NUMBER FROM DRIVER_ORDER where ID = last_insert_id()
  </selectKey>
  INSERT INTO 
   DRIVER_ORDER(ID,ORDER_NUMBER,AREA_START,AREA_END,CREATE_USER,CREATE_TIME) 
  VALUES
   (#{id},
    #{orderNumber,jdbcType=VARCHAR},
    #{areaStart,jdbcType=VARCHAR},
    #{areaEnd,jdbcType=VARCHAR},
    #{createUser,jdbcType=VARCHAR},
    now())
</insert> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM