Create Operation

To insert records into a table, the first step is to create the SQL Map. Let us create a parameter map as –follows:

<parameterMap id="EMP_INSERT_PARAM_MAP" class="java.util.HashMap">
<parameter property="EmployeeId" jdbcType="VARCHAR" javaType="java.lang.String" />
<parameter property="EmployeeName" jdbcType="VARCHAR" javaType="java.lang.String" />
<parameter property="dtBirthDate" jdbcType="DATE" javaType="java.util.Date" />
<parameter property="mobileNum" jdbcType="VARCHAR" javaType="java.lang.String" />
</parameterMap>


Now let us define the actual insert query -

<insert id="EMPLOYEE_INSERT_MYAPP" parameterMap="EMP_INSERT_PARAM_MAP" >
INSERT INTO EMPLOYEE ( EMP_ID, EMP_NAME, DOB, MOB_NO)
VALUES ( ?, ?, ?, ?)
</insert>


Now let us proceed with the actual database request invocation -

try {
HashMap empData = getEmployeeDetailsToCreate(); //Custom logic for identifying data of the employee to create
DatabaseRequest dbRequest = new DatabaseRequest(); 
dbRequest.setDataAccessMapKey("EMPLOYEE");
dbRequest.setOperation(DatabaseConstants.INSERT)
dbRequest.setOperationExtension("MYAPP");
dbRequest.setData(empData); //Pass the data to insert 
dbRequest.execute(); //Execute the insert. 
} catch (DatabaseException dbException) {
//Handle the exception appropriately.
}


In this example,it is expected that the empData provides the values under the keys as defined in the parameterMap provided in the SQL map. This can also be achieved without the definition of the parameterMap and using direct inline variable placeholders. And this does not change the way the code is written in any manner! So let us look at that definition:

<insert id="EMPLOYEE_INSERT_MYAPP" parameterClass="java.util.HashMap" >
INSERT INTO EMPLOYEE ( EMP_ID, EMP_NAME, DOB, MOB_NO)
VALUES ( #EmployeeId#, #EmployeeName#, #dtBirthDate#, #mobileNum#)
</insert>


Any exception related to the insert operation is bundled into the DatabaseException thrown by the dbRequest.execute(). This can be handled appropriately as per the needs of the end application.