Returning values from MyBatis mapped methods

前端 未结 5 823
无人及你
无人及你 2020-12-28 08:33

I have a Java project that uses MyBatis to access a PostgreSQL database. PostgreSQL allows to return fields of a newly created row after an INSERT statement, an

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-28 08:54

    There are two ways (at least that I know) to get the ID of the one inserted record:

    For example, we have a class EntityDao:

    public class EntityDao {
         private Long id;
         private String name;
         // other fields, getters and setters
    }
    

    1. Using the insert tag and returning an instance of object

    MyBatis interface

    public interface EntityDaoMapper {
        EntityDao insert(EntityDao entity);
    }
    

    MyBatis XML mapper:

    
        INSERT INTO some_table (name, type, other_fields, etc)
        VALUES (#{name}, #{type}, #{other_fields}, #{etc}) 
    
    

    Sample code:

        EntityDao saved = entityDaoMapper.insert(entityToSave);
        System.out.println(saved.getId());
    

    2. Using select and resultType tags to return the ID of the record only

    MyBatis interface

    public interface EntityDaoMapper {
        Long insert(EntityDao entity);
    }
    

    MyBatis XML mapper:

    
    

    Sample code:

    Long id = entityDaoMapper.insert(entityToSave);
    System.out.println(id);
    

提交回复
热议问题