MyBatis Insert Using Annotations and XML

Dear Readers,

Below is an example of inserting data using mybatis annotations and xml. Both XML and Annotation based inserts should set the newly inserted records id in the given object.

** I am using MySQL auto increment functionality for generating the primary key values.

1. Insert using annotations

package com.mybatis.demo.role.dao;

import java.util.List;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import com.mybatis.demo.role.vo.RoleVO;

public interface RoleDAO {
	String MQL_CREATE_ROLE    = "insert into roles (roleName, roleDescription) values (#{roleName},#{roleDescription})";
	@Insert(MQL_CREATE_ROLE)
	@Options(useGeneratedKeys = true, keyProperty="id")
	public int doCreateRole(RoleVO vo) throws Exception;
}

@Options Annotation

keyProperty
If you have experienced iBatis/ MyBatis Mapping, you might expect a @SelectKey annotation. But the case is slightly different from what you expect it to be. There is a keyProperty attribute under @Options annotation, using which the key property name is identified.
useGeneratedKeys
Attribute specifies that underlying database takes care of generating / auto incrementing the column values. Must be set to true when you are using AutoGenerated field

@Options Annotation
This is pretty straight forward. As usual you will need to pass SQL Query as an argument.

2. Insert Using XML

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.demo.role.dao.RoleDAO">
     <insert id="insertRole" parameterType="Role"  timeout="20000">
        <![CDATA[
            insert into roles(rolename,roledescription) values (#{roleName},#{roleDescription})
        ]]>
        <selectKey resultType="java.lang.Long" keyProperty="id" >
            SELECT LAST_INSERT_ID() AS id
        </selectKey>
     </insert>
</mapper>
LAST_INSERT_ID()
SELECT LAST_INSERT_ID() is MySQL way of selecting the last inserted id from the database. Check out this page for detailed information about this function.
You must be careful to use appropriate database function to get the last inserted value, because this varies from database to database. e.g., In Oracle it is SEQUENCE.NEXTVAL and in MS SQL Server it is @@identity or ident_current()

Rest all tags are self explanatory… I know you are smiling :)

Did you like this? Share it:

Leave a Reply

Categories
open all | close all
Calendar
October 2010
M T W T F S S
« Sep   Jun »
 123
45678910
11121314151617
18192021222324
25262728293031