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
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
}
insert tag and returning an instance of objectMyBatis 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());
select and resultType tags to return the ID of the record onlyMyBatis interface
public interface EntityDaoMapper {
Long insert(EntityDao entity);
}
MyBatis XML mapper:
Sample code:
Long id = entityDaoMapper.insert(entityToSave);
System.out.println(id);