iBatis-Inserting data into database
The greatest feature of iBatis is it?s simplicity, and that is the only reason of being it easier to use in any database application. iBatis makes it really simple to use a database with Java or any other Microsoft applications. In this section we will introduce you with an example which is inserting a row into database. And for this we are using MySQL as a database it is the same one we have used in our previous example. The table name is "Contact" and we have used two files "Contact.java" and "SqlMapConfig.xml" as we did in previous example.
Contact.java
public class Contact {
|
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <settings useStatementNamespaces="true"/> <transactionManager type="JDBC"> <dataSource type="SIMPLE"> <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/> <property name="JDBC.ConnectionURL" value="jdbc:mysql://192.168.10.112:3306/vin"/> <property name="JDBC.Username" value="root"/> <property name="JDBC.Password" value="root"/> </dataSource> </transactionManager> <sqlMap resource="Contact.xml"/> </sqlMapConfig> |
For SQL mapping statement we have used <insert> tag. Inside this tag definition we have defined an "id" which will be used in IbatisInsertion.java file for executing insert query on database.
<selectKey resultClass="int"
keyProperty="id"> select last_insert_id() as id </selectKey> |
Above lines of code points to next row of the table where the next value is to be inserted.
Contact.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap namespace="Contact"> <!--- Inserting data in table --> <!--- Showing all data of table --> |
Full source code of IbatisInsertion.java is as follows:
IbatisInsertion.java
import com.ibatis.common.resources.Resources; Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
|
To run this example :
- Create and save Contact.java and compile it.
- Create and save Contact.xml and SqlMapConfig.xml
- Create and save IbatisInsertion.java and
- execute IbatisInsertion class file and
output on your command prompt will be flashed as
"Record Inserted Successfully"
Output: