Sei sulla pagina 1di 24

iBatis-Showing all data from database

iBatis is a Data persistence framework like Hibernate, JDO and EJB that maps objects
to SQL statements. It is a lightweight framework and persistence API good for persisting
POJOs( Plain Old Java Objects). iBatis is different from Hibernate, JDO since it uses
stored procedures and existing SQL to handle database.

In this tutorial we are going to tell you iBatis configuration for a small application to
run. As it is hard to explain everything in one go… so we have presented this tutorial into
few separate examples. This example is all about to read data from the database and
showing the results on your command prompt. In the second example you will learn to
add more data into the database and after that third example is going to show you how to
delete the data from the records using iBatis.

Now in the first example that is going to show records from the database, we need a
database to run queries, so we are using MySQL 5.0 as database for this example.

Here we are retrieving contact information of few persons. Table structure of "Contact"
table is as given below:

Creating Database in MySQL

DROP TABLE IF EXISTS


`contact`;

CREATE TABLE `contact` (


`id` int(11) NOT NULL
auto_increment,
`firstName` varchar(20)
default NULL,
`lastName` varchar(20)
default NULL,
`email` varchar(20)
default NULL,
PRIMARY KEY (`id`)
);

According to this table "Contact" we have to make a POJO class. Our example database
"vin" has a "Contact" table, which have four fields as:

• id
• firstName
• lastName
• email

Contact.java

public class Contact {


private String firstName;
private String lastName;
private String email;
private int id;

public Contact() {}

public Contact(
String firstName,
String lastName,
String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

public String getEmail() {


return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

For mapping configuration we need to create "SqlMapConfig.xml" which specifies


following things:

• Namespace prefix for referring mapped statements.


• Our database will be accessed using JDBC
• JDBC driver for MySQL is "com.mysql.jdbc.Driver"
• Connection URL is "jdbc:mysql://192.168.10.112:3306/vin"
• username and password is "root" and "root"
• Our sql statement mappings are described in "Contact.xml"

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>

Mapping file "Contact.xml" is given as follows which is responsible for our application
to execute SQL queries. Full code of Contact.xml is as follows:

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">
<!--- Showing all data of table -->
<select id="getAll"
resultClass="Contact">
select * from contact
</select>
</sqlMap>

Now to show data from database we have created a class "IbatisExample", which reads
configuration from SqlMapConfig.xml and then show all data on your console output.
Full source code of IbatisExample.java is as follows:

IbatisExample.java

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class IbatisExample{


public static void main(String[] args)
throws IOException,SQLException{
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient sqlMap =
SqlMapClientBuilder.buildSqlMapClient(reader);
//Output all contacts
System.out.println("All Contacts");
List<Contact> contacts = (List<Contact>)
sqlMap.queryForList("Contact.getAll",null);
Contact contact = null;
for (Contact c : contacts) {
System.out.print(" " + c.getId());
System.out.print(" " + c.getFirstName());
System.out.print(" " + c.getLastName());
System.out.print(" " + c.getEmail());
contact = c;
System.out.println("");
}
}
}

To run this example you have to follow these steps :

• Create table Contact in your MySQL database


• Download jar file of iBatis(ibatis-common-2.jar,ibatis-dao-2.jar,ibatis-
sqlmap-2.jar) and put it to your lib directory
• Set class path
• Create and save Contact.java and compile it
• Create and save Contact.xml
• now create SqlMapConfig.xml file and finally
• create IbatisExample.java and compile it
• Execute IbatisExample file

Output:

Output on your command prompt would be like as follows.

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 {


private String firstName;
private String lastName;
private String email;
private int id;

public Contact() {}

public Contact(
String firstName,
String lastName,
String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

public String getEmail() {


return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

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 -->

<insert id="insert"
parameterClass="Contact">
insert into contact
(firstName,lastName,email)
values (#firstName#,
#lastName#, #email#)
<selectKey resultClass="int"
keyProperty="id">
select last_insert_id() as id
</selectKey>
</insert>

<!--- Showing all data of table -->


<select id="getAll"
resultClass="Contact">
select * from contact
</select>
</sqlMap>

Full source code of IbatisInsertion.java is as follows:

IbatisInsertion.java

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class IbatisInsertion{


public static void main(String[] args) throws IOException,SQLException
{
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader
);
//Inserting one record in contacts
System.out.println(
"*-------------- Inserting information in Contact Table -----------
*");
Contact contact=new Contact("Amit","Kumar","amit@roseindia.net");
sqlMap.insert("Contact.insert",contact);
System.out.println("|Record Inserted Successfully ");
System.out.println("All Contacts");
List<Contact> contacts = (List<Contact>)
sqlMap.queryForList("Contact.getAll",null);
Contact contactall = new Contact();
for (Contact c : contacts) {
System.out.print(" " + c.getId());
System.out.print(" " + c.getFirstName());
System.out.print(" " + c.getLastName());
System.out.print(" " + c.getEmail());
contact = c;
System.out.println("");
}
System.out.println("==============================================
=");
}
}

To run this example :

1. Create and save Contact.java and compile it.


2. Create and save Contact.xml and SqlMapConfig.xml
3. Create and save IbatisInsertion.java and
4. execute IbatisInsertion class file and output on your command prompt will be
flashed as
"Record Inserted Successfully"

Output:

iBatis Deletion Tutorial


I hope you have completely understood how to insert and show data from database in the
previous examples. So in this example you will learn how to delete the data from
database using iBatis. For that you have to analysis the code to understand clearly what is
happening in this code. But you absolutely need not to create different database, as you
already know that we are using previous MySQL as a database table and our table name
is “Contact”. But you have a choice you can use either this database or create your own
it’s completely up to you! The only thing is that make sure you defined table name
correctly otherwise bug will occur. In case you are following this iBatis tutorial from the
starting then you need not to rewrite the code. Just copy the given code into folder and
execute it finally to delete the data from the database table.

As I earlier mentioned.. In this section of iBatis tutorial we are going to delete records
from Contact table, we are using MySQL database "vin".

Our Contact.java and SqlMapConfig.xml files are same as in previous examples.

Contact.java

public class Contact {


private String firstName;
private String lastName;
private String email;
private int id;

public Contact() {}
public Contact(
String firstName,
String lastName,
String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

public String getEmail() {


return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

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>

In Contact.xml file we are using <delete> tag to delete all records from Contact table.

<delete id="deleteAll"
parameterClass="Contact">
delete from Contact
</delete>

Above lines of code deletes all records from Contact table. Here the defined id
"deleteAll" will be used further in IbatisDeletion class to execute query on the database.

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">
<!--- Delete data from Contact table -->
<delete id="deleteAll"
parameterClass="Contact">
delete from Contact
</delete>

<!--- Showing all data of table -->


<select id="getAll"
resultClass="Contact">
select * from contact
</select>
</sqlMap>

We have imported following packages :


• com.ibatis.common.resources
• com.ibatis.sqlmap.client

for using classes and interfaces of SQL mapping .

Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");


SqlMapClient sqlMap =
SqlMapClientBuilder.buildSqlMapClient(reader);

Above lines of code reads configuration from "SqlMapConfig.xml". Full source code of
IbatisDeletion.java is as follows:

IbatisDeletion.java

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class IbatisDeletion{


public static void main(String[] args)
throws IOException,SQLException{
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient sqlMap =
SqlMapClientBuilder.buildSqlMapClient(reader);
//Deleting all records from contacts
System.out.println("*-- Deleting informations from Contact------
*");
Contact contct=new Contact();
sqlMap.delete("Contact.deleteAll",contct);
System.out.println("|Deleted Record Successfully ");
System.out.println("All Contacts");
List<Contact> contacts = (List<Contact>)
sqlMap.queryForList("Contact.getAll",null);
Contact contact = null;
for (Contact c : contacts) {
System.out.print(" " + c.getId());
System.out.print(" " + c.getFirstName());
System.out.print(" " + c.getLastName());
System.out.print(" " + c.getEmail());
contact = c;
System.out.println("");
}
System.out.println("============================================");
}
}

To run this example follow these steps :

• Create and save Contact.xml and SqlMapConfig.xml


• create and save Contact.java and compile Contact.java
• create IbatisDeletion.java and compile it
• execute IbatisDeletion and you will get following output on your command
prompt

Output:

iBatis Update -Updating data of a table


Add, Update and Delete are very common and essential feature for any database
application. In this iBatis tutorial we have already explained about Insert and Delete in
Java using iBatis, now this section will introduce you how you can update data in data
table with the iBatis. In iBatis executing an update statement is very simple. For updating
you have to add SQL "Update" statement in SQL mapping file "Contact.xml".
Contact.java and SqlMapConfig.xml is same as in our previous examples.

iBatis update statement Example

Contact.java

public class Contact {


private String firstName;
private String lastName;
private String email;
private int id;

public Contact() {}

public Contact(
String firstName,
String lastName,
String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

public String getEmail() {


return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

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>

iBatis Update Query

Here in our example we are updating table with an id as specified in our parameter and
therefore for "id" we have assigned "parameterClass" property value to "long".

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">
<!--- Showing all data of table -->
<select id="getAll"
resultClass="Contact">
select * from contact
</select>
<!--- Update data of Contact table -->
<update id="updateById"
parameterClass="long">
update Contact
set
lastName = 'Raghuwanshi'
where
id=#id#
</update>
</sqlMap>

Now we can execute update command from our java program by the following code as:

sqlMap.update("Contact.updateById",contactId);

Full source code of IbatisUpdate.java is as follows:

IbatisUpdate.java

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class IbatisUpdate{


public static void main(String[] args)
throws IOException,SQLException{
Reader reader = Resources.getResourceAsReader(
"SqlMapConfig.xml"
);
SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
//Updating one record of contact
System.out.println("*---- Updating informations of Contact -----*");
Contact contct=new Contact();
long contactId=1;
sqlMap.update("Contact.updateById",contactId);
System.out.println("|Updated Record Successfully ");
System.out.println("All Contacts");
List<Contact> contacts = (List<Contact>)
sqlMap.queryForList("Contact.getAll",null);
Contact contact = null;
for (Contact c : contacts) {
System.out.print(" " + c.getId());
System.out.print(" " + c.getFirstName());
System.out.print(" " + c.getLastName());
System.out.print(" " + c.getEmail());
contact = c;
System.out.println("");
}
System.out.println("============================================");
}
}

To run this example program of Update statement follow these steps:

1. Create and Save Contact.java and SqlMapConfig.xml


2. Compile Contact.java
3. make Contact.xml
4. create and save IbatisUpdate.java and compile it
5. On executing IbatisUpdate class file you will get this output

Output:
iBatis ResultMap example
If you are working with iBatis Result Map then you must know that iBatis result maps are
used to provide mapping between the result of database query and object properties of it.
And it is the most common and important feature of iBatis. This section of iBatis tutorial
is just an simple introduction to ResultMap. This will familiarize you that how you
can execute an query with ResultMap. Our Contact.java and SqlMapConfig.xml file
have no change and these are as same as in our previous examples. Code for Contact
POJO is as follows:

Contact.java

public class Contact {


private String firstName;
private String lastName;
private String email;
private int id;

public Contact() {}

public Contact(
String firstName,
String lastName,
String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

public String getEmail() {


return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

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 ResultMap we have to use <resultMap></resultMap> tag. It consists of an id which


is required to run this resultMap in our <select> tag's resultMap attribute. Here is the full
code of Contact.xml .

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">
<!--- Showing data by ID -->
<resultMap id="result"
class="Contact">
<result property="id" column="id"/>
<result property="firstName"
column="firstName"/>
<result property="lastName"
column="lastName"/>
<result property="email"
column="email"/>
</resultMap>

<select id="getById"
resultMap="result">
select * from contact where
id=#id#
</select>
</sqlMap>

To run resultMap example we have to include following line in our java code.

sqlMap.queryForObject("Contact.getById",new Integer(1));

Here we have passed id value "1" for showing all information on that id.
IbatisResultMap.java

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class IbatisResultMap{


public static void main(String[] args)
throws IOException,SQLException{
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient sqlMap =
SqlMapClientBuilder.buildSqlMapClient(reader);
//Output all contacts
System.out.println("*------Information by Contact Id--------*");
Contact contact =
(Contact)sqlMap.queryForObject("Contact.getById",new Integer(1));
System.out.println("|Id = " + contact.getId());
System.out.println("|First Name = " + contact.getFirstName());
System.out.println("|Last Name = " + contact.getLastName());
System.out.println("|Email Id = " + contact.getEmail());
System.out.println("==========================================");
}
}

To run this example

• Create and Save Contact.xml and SqlMapConfig.xml


• Create and compile Contact.java
• Create and compile IbatisResultMap.java and
• On executing IbatisResultMap class file all information on that id "1" will be
displayed.

Output:

iBatis Stored Procedure Example


As you have seen in the previous part of tutorials that we can use inline insert , delete,
update SQL commands on our database table with iBatis. Here is the example where you
will see how "Stored Procedures" are called in iBatis ?

As I have mentioned in previous example we are using MySQL database and we are
using a Contact table same as in previous examples. We have created a stored procedure
in "vin" database named as showData() which is showing all contact information of
Contact table. For creating stored procedure first open MySQL and create procedure as
defined below:

DELIMITER $$

DROP PROCEDURE
IF EXISTS
`vin`.`showData`$$

CREATE
PROCEDURE
`vin`.`showData`()
BEGIN
select * from Contact;
END$$

DELIMITER ;

"Contact.java" and "SqlMapConfig.xml" files are same as in our previous examples.

Contact.java

public class Contact {


private String firstName;
private String lastName;
private String email;
private int id;

public Contact() {}

public Contact(
String firstName,
String lastName,
String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

public String getEmail() {


return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

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>

We have only modified "Contact.xml" and using <procedure> tag for calling stored
procedure.

<procedure id="storedInfo"
resultClass="Contact">
{ call showData() }
</procedure>

Above lines of code is calling stored procedure and results contact lists. Full source code
of Contact.xml is as follows:

<?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">
<!--- Calling stored procedure -->
<procedure id="storedInfo"
resultClass="Contact">
{ call showData()}
</procedure>
</sqlMap>

Now we can call this stored procedure as :

sqlMap.queryForList("Contact.storedInfo",null); where "sqlMap" is an object of


SqlMapClient class. Full source code of IbatisStoredProcedure.java is as follows :

IbatisStoredProcedure.java

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class IbatisStoredProcedure{


public static void main(String[] args)
throws IOException,SQLException{
Reader reader =

Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient sqlMap =
SqlMapClientBuilder.buildSqlMapClient(reader);
System.out.println("All Contacts");
List<Contact> contacts = (List<Contact>)
sqlMap.queryForList("Contact.storedInfo",null);
Contact contact = null;
for (Contact c : contacts) {
System.out.print(" " + c.getId());
System.out.print(" " + c.getFirstName());
System.out.print(" " + c.getLastName());
System.out.print(" " + c.getEmail());
contact = c;
System.out.println("");
}
}
}

To run this example follow these steps:

• Create and save Contact.xml and SqlMapConfig.xml


• Create Contact.java and compile it.
• make IbatisStoredProcedure.java and compile it .
• Execute this IbatisStoredProcedure class file and all contact information will be
displayed on your command prompt.

Output:

Potrebbero piacerti anche