Q:

mybatis - insert transaction

mybatis mapper code for insert:
<insert id="insert" parameterType="Shop" useGeneratedKeys="true">
    insert into shop(email, pswd, nickname, mobile, city, create_date, status) values (#{email}, #{pswd}, #{nickname}, #{mobile}, #{city}, #{createDate}, #{status})
    <selectKey keyProperty="id" order="AFTER" resultType="long">
        select currval('shop_id_seq')
    </selectKey>
</insert>

The database is postgresql 9.3.
My doubt is: without explicity transaction, when I retrieve the id from sequence with select currval('shop_id_seq'), is it possible to get the wrong value if other threads are also doing insert?
I thought it won't, because currval() function runs in context of current session, not global session, but I am not that sure.

A:

According to PostgreSQL: Documentation: 9.3: Sequence Manipulation Functions, the sequence function currval:

Return the value most recently obtained by nextval for this sequence in the current session. (An error is reported if nextval has never been called for this sequence in this session.) Because this is returning a session-local value, it gives a predictable answer whether or not other sessions have executed nextval since the current session did.

So you will get the correct value. In another way, the sequences are non-transactional. Each session gets a distinct sequence value. The changes in the sequence can not be undone.

