简体   繁体   中英

How to get ID created from Oracle trigger in MyBatis - Spring Boot

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

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.

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