Java Reference
In-Depth Information
require it to be managed by the database for the session; we just need it generated
and passed back to us.
In both cases, i
BATIS
can help make this easier for you. The
<selectKey>
ele-
ment makes this task transparent to your application (at least in the calling code).
The signature for the
insert
method is:
Object insert(
String id,
Object parameterObject
) throws SQLException;
The reason that the
insert
method returns an
Object
is so that you can get the
key that was generated. For example, if you had this mapped statement and code
in your application that uses the second approach explained earlier:
<insert id="insert">
<selectKey
keyProperty="accountId"
resultClass="int">
SELECT nextVal('account_accountid_seq')
</selectKey>
INSERT INTO Account (
accountId, username, password
) VALUES(
#accountId#, #username#, #password#)
</insert>
Integer returnValue = (Integer) sqlMap.insert(
"Account.insert", account);
the
returnValue
variable would contain your generated key. But there is more—
the
keyProperty
attribute in the
<selectKey>
element tells i
BATIS
to get the value
and set it on the object to be inserted. This means that if you want, you can even
ignore the returned value, because the object that was inserted already has the key
value set for you.
Something to remember is that the
<selectKey>
element defines a mapped
statement, and this mapped statement has access to the same parameter map that
the containing
insert
statement does. So, in the previous example, if you wanted
to select the sequence to use for inserted records, you could do so by using this
mapped statement:
<insert id="insertSequence">
<selectKey keyProperty="accountId" resultClass="int">
SELECT nextVal(#sequence#)
</selectKey>
INSERT INTO Account (
