Ibatis Tutorial



Comments



Description

iBATIS TutorialIBATIS TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i ABOUT THE TUTORIAL iBATIS Tutorial iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBATIS makes it easier to build better database oriented application more quickly and with less code. Audience This tutorial is designed for Java programmers with a need to understand the iBATIS framework in detail along with its architecture and actual usage. This tutorial will bring you at intermediate level of expertise from where you can take yourself at higher level of expertise. Prerequisites Before proceeding with this tutorial you should have a good understanding of Java programming language. Because you are going to deal with SQL mapping, so it is required that you have good understanding on SQL and Database concepts. Copyright & Disclaimer Notice All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at [email protected] TUTORIALS POINT Simply Easy Learning Table of Content iBATIS Tutorial ........................................................................... 2 Audience..................................................................................... 2 Prerequisites .............................................................................. 2 Copyright & Disclaimer Notice ................................................... 2 iBATIS Overview ........................................................................ 5 iBATIS Design Philosophies:...................................................................... 5 Advantages of IBATIS ................................................................................ 5 Pre-Requisite: ............................................................................................ 6 iBATIS Environment ................................................................... 7 iBATIS Installation: ..................................................................................... 7 Database Setup: ........................................................................................ 8 Create SqlMapConfig.xml .......................................................................... 8 iBATIS Create Operation ......................................................... 10 Employee POJO Class:............................................................................ 10 Employee.xml File: ................................................................................... 11 IbatisInsert.java File: ................................................................................ 11 Compilation and Run: ............................................................................... 12 iBATIS Read Operation ............................................................ 13 Employee POJO Class:............................................................................ 13 Employee.xml File: ................................................................................... 14 IbatisRead.java File:................................................................................. 14 Compilation and Run: ............................................................................... 15 iBATIS Update Operation ......................................................... 16 Employee POJO Class:............................................................................ 16 Employee.xml File: ................................................................................... 17 IbatisUpdate.java File:.............................................................................. 18 Compilation and Run: ............................................................................... 18 Ibatis Delete Operation ............................................................ 20 Employee POJO Class:............................................................................ 20 Employee.xml File: ................................................................................... 21 IbatisDelete.java File: ............................................................................... 22 Compilation and Run: ............................................................................... 22 iBATIS Result Maps ................................................................. 24 Employee POJO Class:............................................................................ 24 Employee.xml File: ................................................................................... 25 IbatisResultMap.java File: ........................................................................ 26 Compilation and Run: ............................................................................... 27 TUTORIALS POINT Simply Easy Learning ..........................................iBATIS Stored Procedures ..................................................................................................java File: ..... 32 Example: Dynamic SQL ............................................................................ 35 iBATIS OGNL Expressions ............................................... 37 iBATIS Debugging ...................................... 31 iBATIS Dynamic SQL .............................. 36 The where Statement: ........... 36 The choose....................................................................java File: ........................................................................................................... 45 TUTORIALS POINT Simply Easy Learning ................................................................................................................................................. 34 IbatisReadDy.................................................................................. 43 Step 1: . 33 Employee.................................................................. 43 Step 2: ................................................................................................. 29 Employee.............................................. 43 Download iBATOR: ........................................................................................... 44 Tasks After Running Abator: .. 39 Compilation and Run: ........ 43 Generating Configuration File: ...............................xml File: ...................................................xml File:........... when.............................xml File: ....................... 40 Debug Methods: .................... 44 Step 3: ............................... 30 Compilation and Run: ........... 44 Updating the dao................................................................................................................................................................................................................................................................................................................... 35 The if Statement: ..................................................................................................xml File: ..................... 40 iBATIS Hibernate................................................................................................................................................................................................................................................................................................................ 38 iBATIS Debugging Example: .................................... otherwise Statement: ....................................... 34 Compilation and Run: ......... 41 iBATOR Introduction ............. 44 Updating the SqlMapConfig............. 29 IbatisSP...... 33 Employee POJO Class:.............................................................................................................. 38 Debugging with Log4J: ............ 37 The foreach Statement: .................................... 28 Employee POJO Class:...................................................................................... Portability: iBATIS can be implemented for nearly any language or platform like Java.NET. A significant difference between iBATIS and other persistence frameworks such as Hibernate is that iBATIS emphasizes use of SQL. Independent Interfaces: iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources. Open source: iBATIS is free and an open source software.1 CHAPTER iBATIS Overview I BATIS is a persistence framework which automates the mapping between SQL databases and objects in Java.NET. Fast Development: iBATIS's philosophy is to do all it can to facilitate hyper-fast development. and you have full access to all of the features of SQL. . Ruby. Supports Inline SQL: No precompiler is needed. iBATIS is what is known as a data mapper and takes care of mapping the parameters and results between the class properties and the columns of the database table. iBATIS Design Philosophies: iBATIS comes with the following design philosophies:      Simplicity: iBATIS is widely regarded as being one of the simplest persistence frameworks available today. TUTORIALS POINT Simply Easy Learning . and the application is easier to deploy and test. and C# for Microsoft . and Ruby on Rails. Supports Dynamic SQL: iBATIS provides features for dynamically building SQL queries based on parameters. Advantages of IBATIS Here are few advantages of using IBATIS:    Suppports Stored procedures: iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database. while other frameworks typically use a custom query language such has the Hibernate Query Language (HQL) or Enterprise JavaBeans Query Language (EJB QL). iBATIS is a lightweight framework and persistence API good for persisting POJOs( Plain Old Java Objects). The mappings are decoupled from the application logic by packaging the SQL statements in XML configuration files. and is more portable. such as lazy loading. Supports O/RM: iBATIS supports many of the same features as an O/RM tool. you make sure that you understand the basics of procedural and object-oriented programming: control structures. runtime code generation. join fetching. iBATIS makes use of JAVA programming language while developing database oriented application. objects etc. caching. TUTORIALS POINT Simply Easy Learning . classes. To understand JAVA in detail you can go through our JAVA Tutorial. data structures and variables. and inheritance Pre-Requisite: Before you proceed. txt inflating: notice. you would have to setup your envrionment properly.3.726.4. This tutorial would guide you with few steps to achieve a working environment.jar inflating: license.4.jar file(s) appropriately. iBATIS Installation: Here are the simple steps you would need to carry out to install iBATIS on your Linux machine:  Download latest version of iBATIS from Download iBATIS.zip inflating: META-INF/MANIFEST.3.2 CHAPTER iBATIS Environment B efore you start with actual development with iBATIS.  Set PATH and CLASSPATH variables at the extracted .MF creating: doc/ creating: lib/ creating: simple_example/ creating: simple_example/com/ creating: simple_example/com/mydomain/ creating: simple_example/com/mydomain/data/ creating: simple_example/com/mydomain/domain/ creating: src/ inflating: doc/dev-javadoc.zip inflating: jar-dependencies.4.jar TUTORIALS POINT Simply Easy Learning . Here are the steps I carried out on my linux machine after downloading iBATIS binary file: $ unzip ibatis-2.txt inflating: lib/ibatis-2.726.726.3.txt $pwd /var/home/ibatis $set PATH=$PATH:/var/home/ibatis/ $set CLASSPATH=$CLASSPATH:/var/home/ibatis\ /lib/ibatis-2.  Unzip the downloaded file to extract .jar file from the bundle and keep it in appropriate lib directory.zip inflating: doc/user-javadoc.txt inflating: release. Username" value="root"/> <property name="JDBC.MaximumActiveConnections" value="10"/> TUTORIALS POINT Simply Easy Learning .xml file empty and we would conver its content in subsequent chapters.0//EN" "http://ibatis.org/dtd/sql-map-config-2. Based on the above assumption we have to create an XML configuration file with nameSqlMapConfig.xml file: <property name="JDBC.Driver"/> <property name="JDBC.  JDBC driver for MySQL is "com.apache. first_name VARCHAR(20) default NULL.AutoCommit" value="true"/> <property name="Pool.mysql.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.xml". Create SqlMapConfig.Driver" value="com.mysql.dtd"> <sqlMapConfig> <settings useStatementNamespaces="true"/> <transactionManager type="JDBC"> <dataSource type="SIMPLE"> <property name="JDBC.org//DTD SQL Map Config 2. salary INT default NULL.  We would use username and password is "root" and "root".  Connection URL is "jdbc:mysql://localhost:3306/testdb". This is where you need to provide all configurations required for iBatis: It is important that both the files SqlMapConfig.jdbc.xml Consider the following:  We are going to use JDBC to access the database testdb. <?xml version="1. PRIMARY KEY (id) ).xml"/> </sqlMapConfig> There are other optional properties which you can set using SqlMapConfig.jdbc.apache. last_name VARCHAR(20) default NULL.Password" value="root"/> </dataSource> </transactionManager> <sqlMap resource="Employee.ConnectionURL" value="jdbc:mysql://localhost:3306/testdb"/> <property name="JDBC.xml should be present in the class path.xml and Employee.  Our sql statement mappings for all the operations would be described in "Employee. For now we would keep Employee.Database Setup: Create EMPLOYEE table in any MySQL database using the following syntax: mysql> CREATE TABLE EMPLOYEE ( id INT NOT NULL auto_increment.Driver".xml with the following content. MaximumCheckoutTime" value="150000"/> <property name="Pool.PingEnabled" value="false"/> TUTORIALS POINT Simply Easy Learning .PingQuery" value="select 1 from Employee"/> <property name="Pool.MaximumIdleConnections" value="5"/> <property name="Pool.<property name="Pool.MaximumTimeToWait" value="500"/> <property name="Pool. This class describes the objects that will "model" database table rows. private String last_name.java file as follows: public class Employee { private int id. Next chapter would show you how to get value of individual fields. We have following EMPLOYEE table in MySQL: CREATE TABLE EMPLOYEE ( id INT NOT NULL auto_increment. Employee POJO Class: We would create Employee class in Employee. salary INT default NULL. TUTORIALS POINT Simply Easy Learning . first_name VARCHAR(20) default NULL. Write.salary = salary. */ public Employee() {} public Employee(String fname. this.3 CHAPTER iBATIS Create Operation T o perform any CRUD ( Create. String lname. The POJO class would have implementation for all the methods required to perform desired operations.first_name = fname. you would need to create a POJOs (Plain Old Java Objects) class corresponding to the table. } } /* End of Employee */ You can define methods to set individual fields in the table. private String first_name. Update and Delete) operation using iBATIS. int salary) { this. this. PRIMARY KEY (id) ). /* Define constructors for the Employee class. private int salary.last_name = lname. last_name VARCHAR(20) default NULL. java.ibatis. last_name.println("Going to insert record.0//EN" "http://ibatis. */ System.sqlmap.apache.java File: This file would have application level logic to insert records in the Employee table: import import import import import import com.common. IbatisInsert. Employee em = new Employee("Zara". or SERIAL column or you have defined a SEQUENCE/GENERATOR.xml File: To define SQL mapping statement using iBATIS.dtd"> <sqlMap namespace="Employee"> <insert id="insert" parameterClass="Employee"> insert into EMPLOYEE(first_name.Resources.resources. In this example we would pass Employee object as a parameter while calling insertmethod of SqlMap class. double or any class object based on requirement. SqlMapClient smc = SqlMapClientBuilder. 5000).out.sql.java file for executing SQL INSERT query on database... float.println("Record Inserted Successfully "). com..insert".Employee. smc.insert("Employee.SQLException.ibatis.util.org/dtd/sql-map-2.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis. System.org//DTD SQL Map 2. com. If your database table uses an IDENTITY.xml").client.io. <?xml version="1. salary) values (#first_name#.out. you can use the <selectKey> element in an <insert> statement to use or return that database-generated value.ibatis.sqlmap.client.SQLException{ Reader rd = Resources.SqlMapClientBuilder.SqlMapClient. we would use <insert> tag and inside this tag definition we would define an "id" which will be used in IbatisInsert. int. java. /* This would insert one record in Employee table. public class IbatisInsert{ public static void main(String[] args) throws IOException.getResourceAsReader("SqlMapConfig. #last_name#. } } TUTORIALS POINT Simply Easy Learning . AUTO_INCREMENT.buildSqlMapClient(rd).").apache.. em). #salary#) <selectKey resultClass="int" keyProperty="id"> select last_insert_id() as id </selectKey> </insert> </sqlMap> Here parameterClass: could take a value as string.*.*. java. "Ali". and a record would be created in EMPLOYEE table.  Create Employee.  Create IbatisInsert. it should have following result: mysql> select * from EMPLOYEE.xml as shown above.Compilation and Run: Here are the steps to compile and run the above mentioned software.. You would get following result. Record Inserted Successfully Go and check your EMPLOYEE table.java as shown above and compile it..java as shown above and compile it.. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.  Execute IbatisInsert binary to run the program.  Create Employee. +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Zara | Ali | 5000 | +----+------------+-----------+--------+ 1 row in set (0. $java IbatisInsert Going to insert record..00 sec) TUTORIALS POINT Simply Easy Learning . private String last_name. this. private int salary.java file as follows: public class Employee { private int id.4 CHAPTER iBATIS Read Operation L ast chapter has shown how to perform CREATE operation on a table using iBATIS.last_name = lname.salary = salary. String lname.first_name = fname.00 sec) Employee POJO Class: To perform read operation we would modify Employee class in Employee. TUTORIALS POINT Simply Easy Learning . private String first_name. first_name VARCHAR(20) default NULL. This table is having only one record as follows: mysql> select * from EMPLOYEE. */ public Employee() {} public Employee(String fname. salary INT default NULL. last_name VARCHAR(20) default NULL. This chapter would show you how to read a table using iBATIS. int salary) { this. /* Define constructors for the Employee class. We have following EMPLOYEE table in MySQL: CREATE TABLE EMPLOYEE ( id INT NOT NULL auto_increment. this. +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Zara | Ali | 5000 | +----+------------+-----------+--------+ 1 row in set (0. PRIMARY KEY (id) ). } public String getLastName() { return last_name.SqlMapClientBuilder. com.} /* Here are the method definitions */ public int getId() { return id.io.ibatis.sql. } public int getSalary() { return salary. java. #last_name#.apache.org//DTD SQL Map 2.ibatis. java.SQLException. <?xml version="1. Subsequent chapter would demonstrate how you can use WHERE clause with SELECT statement and how you can pass values to that WHERE clause.SqlMapClient.common. } public String getFirstName() { return first_name.xml File: To define SQL mapping statement using iBATIS.util. IbatisRead. java.xml file and inside this tag definition we would define an "id" which will be used in IbatisRead. #salary#) <selectKey resultClass="int" keyProperty="id"> select last_insert_id() as id </selectKey> </insert> <select id="getAll" resultClass="Employee"> SELECT * FROM EMPLOYEE </select> </sqlMap> Here we did not use WHERE clause with SQL SELECT statement. last_name.client.Resources.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.ibatis.client.*.java file for executing SQL SELECT query on database. com.0//EN" "http://ibatis. we would add <select> tag in Employee.*. public class IbatisRead{ public static void main(String[] args) TUTORIALS POINT Simply Easy Learning .apache. } } /* End of Employee */ Employee.dtd"> <sqlMap namespace="Employee"> <insert id="insert" parameterClass="Employee"> INSERT INTO EMPLOYEE(first_name.sqlmap.java File: This file would have application level logic to read records from the Employee table: import import import import import import com.sqlmap.org/dtd/sql-map-2.resources. salary) values (#first_name#. /* This would read all records from the Employee table..  Create Employee.").out. em = e..getAll".SQLException{ Reader rd = Resources.xml").out. Going to read records. } } Compilation and Run: Here are the steps to compile and run the above mentioned software.println("").java as shown above and compile it. Employee em = null. System..getFirstName()).out.buildSqlMapClient(rd)..  Execute IbatisRead binary to run the program. for (Employee e : ems) { System. System..print(" " + e.getId()). System. and a record would be read from the EMPLOYEE table.  Create Employee..print(" " + e. SqlMapClient smc = SqlMapClientBuilder.println("Going to read records. You would get following result.out. null).out.getResourceAsReader("SqlMapConfig. */ System. List <Employee> ems = (List<Employee>) smc.print(" " + e.queryForList("Employee. System.java as shown above and compile it.xml as shown above. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.throws IOException..  Create IbatisRead..out.out.println("Records Read Successfully ").print(" " + e.getLastName()).getSalary()). } System. 1 Zara Ali 5000 Record Reads Successfully TUTORIALS POINT Simply Easy Learning . java file as follows: public class Employee { private int id.last_name = lname. +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Zara | Ali | 5000 | +----+------------+-----------+--------+ 1 row in set (0. private String first_name. We have following EMPLOYEE table in MySQL: CREATE TABLE EMPLOYEE ( id INT NOT NULL auto_increment. private int salary.5 CHAPTER iBATIS Update Operation L ast chapter has shown how to perform READ operation on a table using iBATIS. this. first_name VARCHAR(20) default NULL. last_name VARCHAR(20) default NULL. private String last_name. PRIMARY KEY (id) ).first_name = fname. This table is having only one record as follows: mysql> select * from EMPLOYEE. String lname.00 sec) Employee POJO Class: To perform udpate operation you would need to modify Employee. salary INT default NULL. */ public Employee() {} public Employee(String fname. TUTORIALS POINT Simply Easy Learning . This chapter would show you how you can update records in a table using iBATIS. this. int salary) { this.salary = salary. /* Define constructors for the Employee class. #last_name#.} /* Here are the required method definitions */ public int getId() { return id.salary = salary. <?xml version="1.org/dtd/sql-map-2. } public int getSalary() { return salary.id = id. } public void setId(int id) { this. } public String getFirstName() { return first_name. } public void setFirstName(String fname) { this.apache. salary) values (#first_name#. last_name.xml File: To define SQL mapping statement using iBATIS.org//DTD SQL Map 2. } } /* End of Employee */ Employee.first_name = fname. } public void setlastName(String lname) { this.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis. we would add <update> tag in Employee.last_name = lname.0//EN" "http://ibatis. } public String getLastName() { return last_name. } public void setSalary(int salary) { this.apache. #salary#) <selectKey resultClass="int" keyProperty="id"> select last_insert_id() as id </selectKey> </insert> <select id="getAll" resultClass="Employee"> SELECT * FROM EMPLOYEE </select> <update id="update" parameterClass="Employee"> UPDATE EMPLOYEE SET first_name = #first_name# WHERE id = #id# TUTORIALS POINT Simply Easy Learning .dtd"> <sqlMap namespace="Employee"> <insert id="insert" parameterClass="Employee"> INSERT INTO EMPLOYEE(first_name.xml file and inside this tag definition we would define an "id" which will be used in IbatisUpdate.java file for executing SQL UPDATE query on database. setFirstName( "Roma").client.. java..println("Records Read Successfully ").getId()).. public class IbatisUpdate{ public static void main(String[] args) throws IOException. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.</update> </sqlMap> IbatisUpdate. */ System.*.buildSqlMapClient(rd).sqlmap.out.xml").SqlMapClient. System.").common. } } Compilation and Run: Here are the steps to compile and run the above mentioned software. } System. for (Employee e : ems) { System.sql. /* This would update one record in Employee table. smc. Employee em = null.java File: This file would have application level logic to update records into the Employee table: import import import import import import com.  Create Employee. java. com.out..xml as shown above.ibatis. System. com.getFirstName()).out.Resources.client.*.util..print(" " + e.io.getResourceAsReader("SqlMapConfig. TUTORIALS POINT Simply Easy Learning .print(" " + e.setId(1).java as shown above and compile it. java. em = e.SQLException{ Reader rd = Resources.queryForList("Employee. null).getAll". Employee rec = new Employee().  Create IbatisUpdate.out.println("Record updated Successfully "). rec.print(" " + e.println("Going to read records.  Create Employee.update("Employee. System.sqlmap. rec ).out.out. System.update".out.. SqlMapClient smc = SqlMapClientBuilder.SQLException.SqlMapClientBuilder..print(" " + e.getLastName()).getSalary()).java as shown above and compile it.println("Going to update record.out.resources. System.out. List <Employee> ems = (List<Employee>) smc. rec. System.").println("").ibatis.ibatis.. Record updated Successfully Going to read records.. 1 Roma Ali 5000 Records Read Successfully TUTORIALS POINT Simply Easy Learning .. You would get following result.. and a record would be updated in EMPLOYEE table and later same record would be read from the EMPLOYEE table. Execute IbatisUpdate binary to run the program... Going to update record.... private String first_name. */ public Employee() {} public Employee(String fname. String lname.first_name = fname.java file. TUTORIALS POINT Simply Easy Learning .salary = salary.last_name = lname. So let us keep it as it is in last chapter. this. PRIMARY KEY (id) ).00 sec) Employee POJO Class: To perform delete operation you do need to modify Employee. public class Employee { private int id. salary INT default NULL. /* Define constructors for the Employee class.6 CHAPTER Ibatis Delete Operation T his chapter would teach you how you can delete records from a table using iBATIS. Assume this table is having two records as follows: mysql> select * from EMPLOYEE. private int salary. private String last_name. last_name VARCHAR(20) default NULL. We have following EMPLOYEE table in MySQL: CREATE TABLE EMPLOYEE ( id INT NOT NULL auto_increment. int salary) { this. first_name VARCHAR(20) default NULL. this. +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Zara | Ali | 5000 | | 2 | Roma | Ali | 3000 | +----+------------+-----------+--------+ 2 row in set (0. apache.last_name = lname.org/dtd/sql-map-2. } public int getSalary() { return salary. salary) values (#first_name#.org//DTD SQL Map 2. <?xml version="1.apache.0//EN" "http://ibatis.} /* Here are the required method definitions */ public int getId() { return id. we would add <delete> tag in Employee. } public String getLastName() { return last_name.xml file and inside this tag definition we would define an "id" which will be used in IbatisDelete.java file for executing SQL DELETE query on database. } public void setId(int id) { this. #salary#) <selectKey resultClass="int" keyProperty="id"> select last_insert_id() as id </selectKey> </insert> <select id="getAll" resultClass="Employee"> SELECT * FROM EMPLOYEE </select> <update id="update" parameterClass="Employee"> UPDATE EMPLOYEE SET first_name = #first_name# WHERE id = #id# TUTORIALS POINT Simply Easy Learning . } } /* End of Employee */ Employee.id = id. #last_name#.xml File: To define SQL mapping statement using iBATIS.first_name = fname. } public void setlastName(String lname) { this. } public void setSalary(int salary) { this.salary = salary. } public void setFirstName(String fname) { this. } public String getFirstName() { return first_name.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.dtd"> <sqlMap namespace="Employee"> <insert id="insert" parameterClass="Employee"> INSERT INTO EMPLOYEE(first_name. last_name. resources.client.getAll". com.getSalary()). em = e.util.common. System. TUTORIALS POINT Simply Easy Learning . id ).print(" " + e.out.").print(" " + e.println("Record deleted Successfully ").ibatis. System.. for (Employee e : ems) { System. System.SqlMapClientBuilder.client.out.println("").java File: This file would have application level logic to delete records from the Employee table: import import import import import import com.delete".getLastName()).io.println("Records Read Successfully ").out. List <Employee> ems = (List<Employee>) smc. java.*.out.sqlmap.buildSqlMapClient(rd). */ System.print(" " + e. java. com.sql.out.. java.Resources.out. System.SQLException.out...ibatis.  Create Employee.queryForList("Employee.delete("Employee.</update> <delete id="delete" parameterClass="int"> DELETE FROM EMPLOYEE WHERE id = #id# </delete> </sqlMap> IbatisDelete. } } Compilation and Run: Here are the steps to compile and run the above mentioned software.xml as shown above.getId()). } System..out. int id = 1.sqlmap.SQLException{ Reader rd = Resources. Employee em = null. smc.getResourceAsReader("SqlMapConfig.. SqlMapClient smc = SqlMapClientBuilder.getFirstName()). System.SqlMapClient. public class IbatisDelete{ public static void main(String[] args) throws IOException.println("Going to delete record. null). /* This would delete one record in Employee table. System.*.xml").")..ibatis.out.print(" " + e.println("Going to read records.. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.  Create Employee.... would be deleted in EMPLOYEE table and rest of the records would be read from the EMPLOYEE table..  Execute IbatisDelete binary to run the program..java as shown above and compile it. and a record with ID = 1. Going to delete record.... 2 Roma Ali 3000 Records Read Successfully TUTORIALS POINT Simply Easy Learning . You would get following result.  Create IbatisDelete. Record deleted Successfully Going to read records.java as shown above and compile it. The design of the ResultMaps is such that simple statements don't require explicit result mappings at all. last_name VARCHAR(20) default NULL. You can reduce upto 90% JDBC coding by using iBATIS ResultMap and in some cases allows you to do things that JDBC does not even support. This chapter would give you just a simple introduction of iBATIS ResultMap. public class Employee { private int id. TUTORIALS POINT Simply Easy Learning . private String last_name. We have following EMPLOYEE table in MySQL: CREATE TABLE EMPLOYEE ( id INT NOT NULL auto_increment. you do need to modify Employee. first_name VARCHAR(20) default NULL. This table is having two records as follows: mysql> select * from EMPLOYEE.7 CHAPTER iBATIS Result Maps T he resultMap element is the most important and powerful element in iBATIS. +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Zara | Ali | 5000 | | 2 | Roma | Ali | 3000 | +----+------------+-----------+--------+ 2 row in set (0.java file. So let us keep it as it is in last chapter. private int salary. salary INT default NULL. PRIMARY KEY (id) ). private String first_name.00 sec) Employee POJO Class: To use iBATIS ResultMap. and more complex statements require no more than is absolutely necessary to describe the relationships. apache.last_name = lname.first_name = fname. salary) values (#first_name#.0//EN" "http://ibatis. } public String getLastName() { return last_name. } public void setFirstName(String fname) { this. } public void setId(int id) { this.dtd"> <sqlMap namespace="Employee"> <!-.first_name = fname. String lname.xml file to introduce <resultMap></resultMap> tag./* Define constructors for the Employee class. } public int getSalary() { return salary. #last_name#.Perform Insert Operation --> <insert id="insert" parameterClass="Employee"> INSERT INTO EMPLOYEE(first_name. int salary) { this. } public String getFirstName() { return first_name. } public void setSalary(int salary) { this.org/dtd/sql-map-2.apache. This tag would have an id which is required to run this resultMap in our <select> tag's resultMap attribute.org//DTD SQL Map 2. } public void setlastName(String lname) { this. this. #salary#) <selectKey resultClass="int" keyProperty="id"> select last_insert_id() as id </selectKey> </insert> TUTORIALS POINT Simply Easy Learning .salary = salary.id = id. last_name. */ public Employee() {} public Employee(String fname. <?xml version="1.xml File: Here we would modify Employee.last_name = lname. this. } /* Here are the required method definitions */ public int getId() { return id.salary = salary. } } /* End of Employee */ Employee.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis. com. java.Perform Delete Operation --> <delete id="delete" parameterClass="int"> DELETE FROM EMPLOYEE WHERE id = #id# </delete> <!-.queryForObject ("Employee. java. System..Perform Update Operation --> <update id="update" parameterClass="Employee"> UPDATE EMPLOYEE SET first_name = #first_name# WHERE id = #id# </update> <!-.println("Going to read record. System. int id = 1.*. java.sqlmap.println("ID: " + e. Employee e = (Employee)smc.SqlMapClientBuilder.getSalary()).getFirstName()).java File: This file would have application level logic to read records from the Employee table using ResultMap: import import import import import import com.println("Salary: " + e. System. id).getLastName()). public class IbatisResultMap{ public static void main(String[] args) throws IOException.xml").SQLException{ Reader rd = Resources.resources.common..out.")..useResultMap".buildSqlMapClient(rd).out.util. SqlMapClient smc = SqlMapClientBuilder.out. System.sql.SQLException.Using ResultMap --> <resultMap id="result" class="Employee"> <result property="id" column="id"/> <result property="first_name" column="first_name"/> <result property="last_name" column="last_name"/> <result property="salary" column="salary"/> </resultMap> <select id="useResultMap" resultMap="result"> SELECT * FROM EMPLOYEE WHERE id=#id# </select> </sqlMap> IbatisResultMap. System.out.client.*. System.out.ibatis.println("Last Name: " + e.println("Record read Successfully "). com.SqlMapClient.ibatis. TUTORIALS POINT Simply Easy Learning .Perform Read Operation --> <select id="getAll" resultClass="Employee"> SELECT * FROM EMPLOYEE </select> <!-.getId())..Resources.out.ibatis.println("First Name: " + e.client.<!-.getResourceAsReader("SqlMapConfig.io.sqlmap.  Execute IbatisResultMap binary to run the program.  Create IbatisResultMap. You would get following result which is a read operation on the EMPLOYEE table..  Create Employee...  Create Employee.} } Compilation and Run: Here are the steps to compile and run the above mentioned software.xml as shown above. ID: 1 First Name: Zara Last Name: Ali Salary: 5000 Record read Successfully TUTORIALS POINT Simply Easy Learning .java as shown above and compile it. Going to read record.java as shown above and compile it.. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution. `getEmp` $$ CREATE PROCEDURE `testdb`. Before procedding for this chapter you can go through MySQL Stored Procedure. salary INT default NULL. first you need to understand how we create a stored procedure in MySQL.00 sec) TUTORIALS POINT Simply Easy Learning . first_name VARCHAR(20) default NULL. Consider EMPLOYEE table is having two records as follows: mysql> select * from EMPLOYEE. END $$ DELIMITER. Let us have following stored procedure created in MySQL database. DELIMITER $$ DROP PROCEDURE IF EXISTS `testdb`.8 CHAPTER iBATIS Stored Procedures T his is very much possible to call a stored procedure using iBATIS configuration. To understand this chapter. last_name VARCHAR(20) default NULL. We have following EMPLOYEE table in MySQL: CREATE TABLE EMPLOYEE ( id INT NOT NULL auto_increment. PRIMARY KEY (id) ). +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Zara | Ali | 5000 | | 2 | Roma | Ali | 3000 | +----+------------+-----------+--------+ 2 row in set (0.`getEmp` (IN empid INT) BEGIN SELECT * FROM EMPLOYEE WHERE ID = empid. you do need to modify Employee.0//EN" "http://ibatis. <?xml version="1. } public int getSalary() { return salary. So let us keep it as it is in last chapter.first_name = fname. } public void setlastName(String lname) { this.salary = salary.id = id.last_name = lname. public class Employee { private int id.Employee POJO Class: To use stored procedure.org/dtd/sql-map-2. private int salary.xml file to introduce <procedure></procedure> and <parameterMap></parameterMap> tags. } public void setFirstName(String fname) { this. String lname. this. } /* Here are the required method definitions */ public int getId() { return id.dtd"> <sqlMap namespace="Employee"> TUTORIALS POINT Simply Easy Learning .0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache. private String first_name. int salary) { this.salary = salary.xml File: Here we would modify Employee.first_name = fname. } public String getLastName() { return last_name. } } /* End of Employee */ Employee.java file. /* Define constructors for the Employee class. */ public Employee() {} public Employee(String fname. } public void setId(int id) { this.org//DTD SQL Map 2. this.last_name = lname. private String last_name. Here <procedure></procedure> tag would have an id which we would use in our application to call the stored procedure.apache. } public String getFirstName() { return first_name. } public void setSalary(int salary) { this. ibatis. TUTORIALS POINT Simply Easy Learning .ibatis.<!-.client. #last_name#. #salary#) <selectKey resultClass="int" keyProperty="id"> select last_insert_id() as id </selectKey> </insert> <!-.xml"). SqlMapClient smc = SqlMapClientBuilder. java.ibatis.io. com. last_name.Perform Delete Operation --> <delete id="delete" parameterClass="int"> DELETE FROM EMPLOYEE WHERE id = #id# </delete> <!-.SqlMapClientBuilder.Integer" mode="IN"/> </parameterMap> </sqlMap> IbatisSP.Resources.buildSqlMapClient(rd).sqlmap.SqlMapClient.sql. salary) values (#first_name#.SQLException{ Reader rd = Resources.Perform Update Operation --> <update id="update" parameterClass="Employee"> UPDATE EMPLOYEE SET first_name = #first_name# WHERE id = #id# </update> <!-.client.lang.common.*.To call stored procedure. java.resources. com.java File: This file would have application level logic to read name of the employee from the Employee table using ResultMap: import import import import import import com. java. --> <procedure id="getEmpInfo" resultClass="Employee" parameterMap="getEmpInfoCall"> { call getEmp( #acctID# ) } </procedure> <parameterMap id="getEmpInfoCall" class="map"> <parameter property="acctID" jdbcType="INT" javaType="java. public class IbatisSP{ public static void main(String[] args) throws IOException.Perform Read Operation --> <select id="getAll" resultClass="Employee"> SELECT * FROM EMPLOYEE </select> <!-.util.*.Perform Insert Operation --> <insert id="insert" parameterClass="Employee"> INSERT INTO EMPLOYEE(first_name.sqlmap.getResourceAsReader("SqlMapConfig.SQLException. ").getFirstName()). System..  Execute IbatisSP binary to run the program. You would get following result: Going to read record.println("Going to read employee name. System.  Create Employee..out.. ID: 1 First Name: Zara Last Name: Ali Salary: 5000 Record read Successfully TUTORIALS POINT Simply Easy Learning .  Create Employee.int id = 1..out.out.getEmpInfo"..queryForObject ("Employee.println("Record name Successfully "). Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution. id)...java as shown above and compile it.java as shown above and compile it. Employee e = (Employee)smc.println("First Name: " + e. System. } } Compilation and Run: Here are the steps to compile and run the above mentioned software..  Create IbatisSP.xml as shown above. <select id="findByID" resultClass="Employee"> SELECT * FROM EMPLOYEE <dynamic prepend="WHERE "> <isNotEmpty property="id"> id = #id# </isNotEmpty> </dynamic> TUTORIALS POINT Simply Easy Learning .. All the logic is put in .. Sometime you have changing WHERE clause criterion based on your parameter object's state.dtd"> <sqlMap namespace="Employee"> <select id="findByID" resultClass="Employee"> SELECT * FROM EMPLOYEE <dynamic prepend="WHERE "> <isNull property="id"> id IS NULL </isNull> <isNotNull property="id"> id = #id# </isNotNull> </dynamic> </select> </sqlMap> You can check condition using <isNotEmpty> tag as follows.org//DTD SQL Map 2..apache..XML file using some additional tags. .org/dtd/sql-map-2... <?xml version="1....0//EN" "http://ibatis..0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.. Here condition would be added only when passed property is not empty...apache...9 CHAPTER iBATIS Dynamic SQL U sing dynamic queries is a very powerful feature of iBatis.. Following is an example where SELECT statement would work in two ways:  If you would pass an ID then it would return all the records corresponding to that ID. In such situation iBATIS provides a set of dynamic SQL tags that can be used within mapped statements to enhance the reusability and flexibility of the SQL..  otherwise it would return all the records where employee ID is set to NULL. .00 sec) Employee POJO Class: To perform read operation. Example: Dynamic SQL Following example would show how you can write SELECT statement with dynamic SQL..java file as follows: public class Employee { private int id.... PRIMARY KEY (id) )... let us have Employee class in Employee....</select> ... last_name VARCHAR(20) default NULL. Here would be your SELECT statement: .. If you want a query where we can select on id and/or first name of an Employee.... first_name VARCHAR(20) default NULL. */ public Employee() {} public Employee(String fname... String lname.. we have following EMPLOYEE table in MySQL: CREATE TABLE EMPLOYEE ( id INT NOT NULL auto_increment. <select id="findByID" resultClass="Employee"> SELECT * FROM EMPLOYEE <dynamic prepend="WHERE "> <isNotEmpty prepend="AND" property="id"> id = #id# </isNotEmpty> <isNotEmpty prepend="OR" property="first_name"> first_name = #first_name# </isNotEmpty> </dynamic> </select> .. This table is having only one record as follows: mysql> select * from EMPLOYEE.. /* Define constructors for the Employee class..... private int salary......... private String last_name..... +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Zara | Ali | 5000 | | 2 | Roma | Ali | 3000 | | 3 | Noha | Ali | 7000 | +----+------------+-----------+--------+ 3 row in set (0... private String first_name......... int salary) { TUTORIALS POINT Simply Easy Learning .... Consider.. salary INT default NULL. client.java File: This file would have application level logic to read conditional records from the Employee table: import import import import import import com.first_name = fname.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache. } /* Here are the method definitions */ public int getId() { return id. this. IbatisReadDy. com.0//EN" "http://ibatis. com. public class IbatisReadDy{ public static void main(String[] args) throws IOException.salary = salary.this. } } /* End of Employee */ Employee.resources.*. java.sql.common.org/dtd/sql-map-2.last_name = lname.ibatis. <?xml version="1.xml file and inside this tag definition we would define an "id" which will be used in IbatisReadDy.*. } public String getLastName() { return last_name.sqlmap.apache. this.SqlMapClientBuilder.sqlmap.SqlMapClient.io.java file for executing Dynamic SQL SELECT query on database.SQLException.ibatis.util.org//DTD SQL Map 2. java.Resources. java.dtd"> <sqlMap namespace="Employee"> <select id="findByID" resultClass="Employee"> SELECT * FROM EMPLOYEE <dynamic prepend="WHERE "> <isNotNull property="id"> id = #id# </isNotNull> </dynamic> </select> </sqlMap> Above SELECT statement would work in two ways (i) If you would pass an ID then it would return records corresponding to that ID (ii) otherwise it would return all the records.client.ibatis. we would add following modified <select> tag in Employee. } public int getSalary() { return salary.xml File: To define SQL mapping statement using iBATIS. } public String getFirstName() { return first_name.SQLException{ TUTORIALS POINT Simply Easy Learning . .*/ System. otherwise Statement  where Statement TUTORIALS POINT Simply Easy Learning .getSalary()).print(" " + e. } System.println("Going to read records. Going to read records..").getLastName()).. You would get following result.  if Statement  choose.  Create Employee. em = e. when.println("Records Read Successfully ").out.print(" " + e. Employee rec = new Employee(). Employee em = null.out.setId(1).java as shown above and compile it..findByID".. and a record would be read from the EMPLOYEE table.out. SqlMapClient smc=SqlMapClientBuilder. System.. rec.buildSqlMapClient(rd).findByID". System.getId()). for (Employee e : ems) { System.out. /* This would read all records from the Employee table. System. rec).print(" " + e.queryForList("Employee.  Create Employee..out.xml"). Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.  Execute IbatisReadDy binary to run the program.java as shown above and compile it.  Create IbatisReadDy. } } Compilation and Run: Here are the steps to compile and run the above mentioned software.getFirstName()).xml as shown above. null). List <Employee> ems = (List<Employee>) smc.. iBATIS OGNL Expressions iBATIS provides powerful OGNL based expressions to eliminate most of the other elements.Reader rd=Resources. System.getResourceAsReader("SqlMapConfig.out.print(" " + e.queryForList("Employee.println("").out. 1 Zara Ali 5000 Record Reads Successfully Try above example by passing null as smc. For example: <select id="findActiveBlogWithTitleLike" parameterType="Blog" resultType="Blog"> SELECT * FROM BLOG WHERE state = 'ACTIVE. You can include multiple if conditions as follows: The most common thing to do in dynamic SQL is conditionally include a part of a where clause. let's only return featured blogs: <select id="findActiveBlogWithTitleLike" parameterType="Blog" resultType="Blog"> SELECT * FROM BLOG WHERE state = 'ACTIVE. <choose> <when test="title != null"> AND title like #{title} </when> <when test="author != null and author. then only by author if one is provided. then all active Blogs would be returned. Following example would search only on title if one is provided. If neither is provided. it will look for a title with the given likecondition. <if test="title != null"> AND title like #{title} </if> </select> This statement would provide an optional text search type of functionality.name != null"> AND author like #{author} </when> <otherwise> AND featured = 1 </otherwise> </choose> </select> TUTORIALS POINT Simply Easy Learning . when. otherwise Statement: iBATIS offers a choose element which is similar to Java's switch statement. foreach Statement The if Statement: The most common thing to do in dynamic SQL is conditionally include a part of a where clause. <if test="title != null"> AND title like #{title} </if> <if test="author != null"> AND author like #{author} </if> </select> The choose. For example: <select id="findActiveBlogWithTitleLike" parameterType="Blog" resultType="Blog"> SELECT * FROM BLOG WHERE state = 'ACTIVE. But if you do pass in a title. If you passed in no title. This helps choose only one case among many options. everything works fine: <select id="findActiveBlogLike" parameterType="Blog" resultType="Blog"> SELECT * FROM BLOG <where> <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null> AND author like #{author} </if> </where> </select> The where element knows to only insert WHERE if there is any content returned by the containing tags. if that content begins with AND or OR. You can build an IN condition as follows: <select id="selectPostIn" resultType="domain.The where Statement: If we look previous examples.Post"> SELECT * FROM POST P WHERE ID in <foreach item="item" index="index" collection="list" open="(" separator="." close=")"> #{item} </foreach> </select> TUTORIALS POINT Simply Easy Learning . declare item and index variables that can be used inside the body of the element. it knows to strip it off. and allows you to specify a collection. It also allows you to specify opening and closing strings. Furthermore. The foreach Statement: The foreach element is very powerful.blog. and add a separator to place in between iterations. What happens if none of the conditions are met? You would end up with SQL that looked like this: SELECT * FROM BLOG WHERE This would fail. but iBATIS has a simple solution with one simple change. java.ResultSet=DEBUG #log4j.Connection=DEBUG # shows parameters inserted into prepared statements #log4j.Statement=DEBUG TUTORIALS POINT Simply Easy Learning .properties file. which is my favorite for logging.com.rootLogger=ERROR.logger.java. iBATIS has built-in logging support and it works with the following logging libraries and searches for them in this order.sql.  Log4J  JDK logging You can use any of the above listed libraries alongwith iBATIS.sql.logger.PreparedStatement=DEBUG # shows query results #log4j.sql. Before proceeding you need to cross check following points:  The Log4J JAR file (log4j-{version}.logger.ibatis=DEBUG # shows SQL of prepared statements #log4j. Following is the of a log4j.java. You can uncomment them if you need additiona debugging information.sql. stdout log4j.  Jakarta Commons Logging (JCL).jar) should be in the CLASSPATH. Debugging with Log4J: Assuming you are going to use Log4J. # Global logging configuration log4j.  You have log4j.logger.properties available in the CLASSPATH.logger. Note that some of the lines are commented out.CHAPTER 10 iBATIS Debugging I t is easy to debug your program while working with iBATIS.java. getLastName()). com. em = e..").apache.getAll". log.getLogger( IbatisUpdate.# Console output log4j. public class IbatisUpdate{ static Logger log = Logger. Employee em = null.stdout.out.print(" " + e.info("Going to update record.print(" " + e.xml").Logger. import org.getSalary()). } log.PatternLayout log4j.common..*. We would use above mentioned property file which lies in CLASSPATH.stdout=org.debug("Going to read records. /* This would insert one record in Employee table. */ log.info("Record updated Successfully ").ConversionPattern=%5p [%t] .getFirstName()). for (Employee e : ems) { System.util. java. System. rec ).ibatis. the Log4J logging library for Java applications. System.log4j.client. log. List <Employee> ems = (List<Employee>) smc. System.client. } } TUTORIALS POINT Simply Easy Learning .SQLException{ Reader rd = Resources. System. rec.getId()).debug("Records Read Successfully ").ibatis. null).*.appender.class.appender.getName()).ConsoleAppender log4j.layout=org.out. Employee rec = new Employee(). java.setFirstName( "Roma").print(" " + e.resources.io.buildSqlMapClient(rd). iBATIS Debugging Example: The following Java class is a very simple example that initializes.ibatis.layout.SQLException.%m%n You can find complete documentation for Log4J from Apaches site: Log4J Documentation..getResourceAsReader("SqlMapConfig.out. SqlMapClient smc = SqlMapClientBuilder..print(" " + e. public static void main(String[] args) throws IOException..update".out.update("Employee.log4j. rec.println("").stdout.apache.sqlmap.").out.apache.SqlMapClientBuilder. com..appender..Resources..log4j. and then uses. import import import import import import com.sql. java.setId(1).queryForList("Employee.SqlMapClient. smc.sqlmap. properties as shown above. fatal(Object message). Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution. Returned connection 28405330 to pool.java as shown above and compile it.  Create log4j. debug(Object message). TUTORIALS POINT Simply Easy Learning .Compilation and Run: Here are the steps to compile and run the above mentioned software. 5000 5000 5000 Debug Methods: In the above example we used only info() method but you can use any of the following methods as per your requirements: public public public public public public void void void void void void trace(Object message). error(Object message). Checked out connection 28405330 from pool. DEBUG [main] DEBUG [main] DEBUG [main] DEBUG [main] 1 Roma Ali 2 Zara Ali 3 Zara Ali Created connection 28405330.  Create IbatisUpdate. You would get following result. warn(Object message). and a record would be updated in EMPLOYEE table and later same record would be read from the EMPLOYEE table. Returned connection 28405330 to pool. info(Object message).  Create Employee.java as shown above and compile it.xml as shown above.  Create Employee.  Execute IbatisUpdate binary to run the program. CHAPTER 11 iBATIS Hibernate T here are major differences between iBatis and Hibernate but both the solutions work well. Personally I would suggest you should use iBATIS if:  You want to create your own SQL's and are willing to maintain them.  Your environment is driven by relational data model. given their specific domain. To count there are few differences:   iBATIS is: o Simpler o Faster development time o Flixable o Much smaller in package size Hibernate: o Generates SQL for you which means you don't spend time on SQL o Provides much more advance cache o Highly scalable Other difference is that iBATIS makes use of SQL which could be database dependent where as Hibernate makes use of HQL which is relatively independent of databases and it is easier to change db in Hibernate. And simply use Hibernate if:  Your environment is driven by object model and wants generates SQL automatically. TUTORIALS POINT Simply Easy Learning .  You have to work existing and complex schema's. Hibernate and iBatis both also have good support from SPRING framework so it should not be a problem to chose one of them. works very well for reporting applications. well you can do it in Hibernate but it is little difficult in comparision of iBATIS. so no need to care about table structures. Use of each of these tools depends on the context you are using them. etc Finally. TUTORIALS POINT Simply Easy Learning . This works very well for stored procedures. As an alternative solution iBATIS maps results sets to objects. Hibernate and iBATIS both are open source Object Relational Mapping(ORM) tools available in the industry. If you are using stored procedures.Hibernate maps your Java POJO objects to the Database tables where as iBatis maps the ResultSet from JDBC API to your POJO Objets. iBATOR generates following artifacts:  SqlMap XML Files  Java Classes to match the primary key and fields of the table(s)  DAO Classes that use the above objects (optional) iBATOR can run as a standalone JAR file. follow these steps: Step 1: Create and fill out a configuration file ibatorConfig. Generating Configuration File: To get up and running quickly with Abator. At a minimum.CHAPTER 12 iBATOR Introduction I BATOR is a code generator for iBATIS. This tutorial would teach you simplest way of generating iBATIS configuration files form command line. TUTORIALS POINT Simply Easy Learning . You can check online documentation: iBATOR Documentation. you must specify:    A <jdbcConnection> element to specify how to connect to the target database.xml appropriately. The standalone JAR includes an Ant task to run iBATOR. or as an Ant task.   You can download zip file from Download iBATOR. iBATOR introspects one or more database tables and will generate iBATIS artifacts that can be used to access the table(s). A <javaModelGenerator> element to specify target package and target project for generated Java model objects A <sqlMapGenerator> element to specify target package and target project for generated SQL map files. or you can run iBATOR from the command line of from Java code. Later you can write your custom SQL code or stored procedure to meet yoru requirements. or as an Eclipse plugin. Download iBATOR: Download the standalone JAR if you are using an IDE other than Eclipse. and SQL map XML files that will be used in an iBATIS session. Abator specific needs in the configuration file are as follows:  Statement namespaces must be enabled. After running Abator. However.  Create or modify the dao.xml file. Each task is described in detail below: Updating the SqlMapConfig. then omit the -overwriteparameter.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis. It will also tell Abator to overwrite any existing Java files with the same name. some of the items in this file relate directly to Abator generated items.xml file (only if using the iBATIS DAO Framework).xml.xml package of your project. Tasks After Running Abator: After you run Abator. The SqlMapConfig.0//EN" TUTORIALS POINT Simply Easy Learning . to specify information for a database connection.xml. If you want to save any existing Java files. you will need to create or modify other iBATIS configuration artifacts. suppose that Abator has generated an SQL Map XML file called MyTable_SqlMap. The main tasks are as follows:  Create or Modify the SqlMapConfig.xml -overwrite This will tell Abator to run using your configuration file.  Abator generated SQL Map XML files must be listed .xml file should have these entries: <?xml version="1.xml File: iBATIS uses an XML file. If there is a conflict. commonly named SqlMapConfig.xml). Step 2: Save the file in some convenient location for example at: \temp\ibatorConfig.apache.  A <daoGenerator> element to specify target package and target project for generated DAO interfaces and classes (you may omit the <daoGenerator> element if you don't wish to generate DAOs). Step 3: Now run Abator from the command line with a command line as follows: java -jar abator.org//DTD SQL Map Config 2. Abator cannot create this file for you because Abator knows nothing about your execution environment. For example.jar -configfile \temp\abatorConfig. you will need to create or modify the standard iBATIS configuration files to make use of your newly generated code. a transaction management scheme. and that the file has been placed in the test. This is explained in next section. At least one database <table> element NOTE: See the XML Configuration File Reference page for an example of an Abator configuration file. Abator will save the newly generated file with a unique name. TUTORIALS POINT Simply Easy Learning .dao.0//EN" "http://ibatis."> <dataSource type=".org/dtd/dao-2.dao package of your project.xml file. The dao.dtd"> <daoConfig> <context> <transactionManager type="SQLMAP"> <property name="SqlMapConfigResource" value="test/SqlMapConfig.MyTableDAO" implementation="test.apache."http://ibatis. Updating the dao.apache.0" encoding="UTF-8"?> <!DOCTYPE daoConfig PUBLIC "-//ibatis.MyTableDAOImpl" /> </context> </daoConfig> NOTE: This step is only required if you generated DAOs for the iBATIS DAO framework.apache.Setup the transaction manager and data source that are appropriate for your environment --> <transactionManager type=". and that the files have been placed in the test. For example..dtd"> <sqlMapConfig> <!-. The iBATIS DAO framework uses this file to control the database connection information for DAOs. and all the Abator generated DAO interfaces and implementation classes.dao. then the files can be listed in any order with repeated <sqlMap> elements after the <transactionManager> element.xml" /> </sqlMapConfig> If there is more than one SQL Map XML file (as is quite common).xml"/> </transactionManager> <!-.. suppose that Abator has generated a DAO interface called MyTableDAO and a implementation class called MyTableDAOImpl..DAO interfaces and implementations should be listed here --> <dao interface="test.SQL Map XML files should be listed here --> <sqlMap resource="test/xml/MyTable_SqlMap.org/dtd/sql-map-config-2."> </dataSource> </transactionManager> <!-. In this file you should specify the path to your SqlMapConfig.Statement namespaces are required for Abator --> <settings useStatementNamespaces="true" /> <!-.xml file should have these entries: <?xml version="1..org//DTD DAO Configuration 2.xml File: The iBATIS DAO framework is configured by an xml file commonly called dao.xml. and also to list the DAO implementation classes and DAO interfaces.
Copyright © 2024 DOKUMEN.SITE Inc.