0

I've seen a couple similar questions, however, I just can't get the correct ID value on my code. It's always returning 1 as the ID after insert.

ItemController.java

@Operation(description = "Insert Test")
    @PostMapping("/item/add")
    @ResponseBody
    void upsertTest(
            @RequestBody itemForm testForm
    ) {
        Long itemId = itemService.getItemId();
        itemForm.setItemId(itemId);
        
        System.out.println("Item ID: " + itemId );
}

ItemService.java

@Service("ItemService")
public class ItemService {

    private final ItemDao itemDao;

    @Autowired
    public ItemService(@Qualifier("itemDao") final ItemDao itemDao) {
        this.itemDao = itemDao;
    }

    public Long getItemId(){
        return itemDao.getItemId();
    }
}

ItemDao.java

@Component("itemDao")
@Repository
public interface ItemDao {
    Long getItemId();
}

ItemDao.xml

<insert id="getItemId" useGeneratedKeys="true" keyProperty="itemId" keyColumn="ITEM_ID">
    INSERT INTO ITEM_ID_TABLE (DUMMY) VALUES (null)
</insert>

And my table is basically 2 columns (ITEM_ID, DUMMY), and has a trigger to insert an ID using a sequence on the ITEM_ID column.

Whenever I do an insert output is:

Item ID: 1

Even when I've done multiple inserts already

G Josh
  • 271
  • 1
  • 5
  • 15
  • result of executing 'INSERT' is number of rows that was added, not id of this row. You can try to rewrite your inserting code and add something that return id. check this: https://stackoverflow.com/questions/5558979/inserting-into-oracle-and-retrieving-the-generated-sequence-id – lczapski Aug 19 '20 at 12:33
  • @G.Josh I would take a look if you could share a small demo project like [these](https://github.com/harawata/mybatis-issues) on GitHub. It should include table/trigger definitions as well. And which version of Oracle do you use? – ave Aug 24 '20 at 21:03

1 Answers1

0

in ItemDao.xml try something like this:

<insert id="getItemId" useGeneratedKeys="true" keyProperty="itemId" keyColumn="ITEM_ID">
    INSERT INTO ITEM_ID_TABLE (DUMMY) VALUES (null)
       <selectKey keyProperty="returnId" resultType="int" order="AFTER">
        SELECT LAST_INSERT_ID();
       </selectKey>
</insert>

Based on this question.

lczapski
  • 4,026
  • 3
  • 16
  • 32