Ibatis Framework Introduction and use

Source: Internet
Author: User

What IBATIS is.

This section describes the individual APIs in IBATIS, and why you might use them, and understand the advantages of IBATIS over other database mapping frameworks.

IBATIS Framework

In short, the IBATIS is made up of two separate frameworks. The Data Mapper framework can be used specifically for or mappings, which are mappings of Java domain objects to relational tables in the database. The DAO framework provides a neat and consistent way to access the underlying data for your application.

IBATIS Data Mapper Framework (data Mapper)

Data Mapper is a framework that executes SQL and maps the results back to an object, so that you do not have to do this manually.

The Data Mapper framework does not require the use of any special version of Java objects. You do not have to implement any interfaces or generate any code, you do not have to create subclasses for some other basic objects or follow any strange conventions, and you do not have to learn the secondary query language specific to the framework.

You can use a simple and straightforward XML format to define how IBATIS maps Java objects to a database. You can define the specific query you want directly with SQL, and optionally use any proprietary SQL that is specific to the database engine you are using. This feature allows you to map objects and perform connections using the way you want.

IBATIS Data Access Objects Framework (DAO framework)

The main goal of the DAO framework is to abstract the presentation and location of the data access layer and persistence layer of the application to keep them away from the business logic of the application. The DAO framework allows you to define interfaces in your application that are responsible for data center operations.

For example, if your application uses direct Java Database connectivity (JDBC) for persistence, the goal of the DAO framework is to abstract these classes and interfaces (such as Connection, PreparedStatement, and ResultSet To keep them away from the application and move down to the persistence layer.

If an application uses HTTP get and POST to obtain and store data for some reason, the purpose of the DAO framework becomes the use of abstract classes, such as httpurlconnection, to keep them away from the business layer of the application. The application can then use the DAO interface to perform operations on the data, and the implementations of these interfaces are abstracted away from the business logic. These implementations can obtain data from a database, a WEB service, or any other source.

The DAO framework is not dependent on the use of the Data Mapper framework. You can choose to use both frameworks in one project (which is pretty good in pairs), or you can use each frame separately. This tutorial series will showcase the benefits of using frameworks separately and using them together.



Advantages of IBATIS

The advantage of IBATIS over some other OR mapping tools is that IBATIS does not use its own proprietary query language, it uses only SQL. Some or mapping tools, such as Hibernate, use their own query language in addition to using SQL. All queries and updates that you want to perform are written in SQL (and stored in an. xml file). Some people may think this is a disadvantage, so they want to completely extract the database from them to avoid the need to write any SQL code. This is one of the reasons many developers like Hibernate. But you might prefer to be able to better control what kind of SQL you will execute when you access the object, rather than be willing to generate it unexpectedly for you in a way that relies on the underlying OR mapping framework. You can tune a query or other statement based on the recommendations of the database administrator (DBA) or the Access plan or query optimizer provided by the tools provided in the relational database management system (RDBMS). Another advantage of direct access to the SQL written for this layer is that you can take advantage of any specialized SQL that the database provides. IBATIS is easy to use. The project has a large number of documents to prove. It has no external dependencies. Some other OR mapping frameworks are loaded with 15 to 20. jar files and rely on specific versions of these files to run the framework. You don't need or want to experience this kind of headaches when developing applications, so using IBATIS without any external dependencies is actually a big advantage. (Note that some optional configurations allow the use of external connection tools or byte code enhancements, but these are not required.) )

It is time to delve into some of the more specific IBATIS concepts and semantics that will eventually lead us to some encodings and examples.

The semantics of Batis Data Mapper

The remainder of this tutorial looks at the Data Mapper framework in a near-exclusive fashion (part 2nd will delve into the DAO framework). This section will introduce the semantics of the Data Mapper.

Mapped Statement

The core function of Data Mapper is around mapped Statement. Mapped Statement can have a framework called the Parameter map (essentially for data entry) and result Map (data output). So mapped Statement is essentially an XML element that contains SQL statements that are responsible for performing certain operations and mapping input/output parameters to Java objects. Listing 3 shows a simple SQL mapped Statement from the Jpetstore demo (see Resources for a link to this download).


Listing 3. A simple SQL mapped Statement



parameterclass= "Account" >
Select USERNAME as value from Signon
</select>

The mapped Statement in Listing 3 is responsible for querying all the values of USERNAME columns in the Signon table. There are several different types of mapped Statement. As you can see, this special mapped Statement is a <select>. In addition to <select>, you can use the IBATIS framework with <statement>, <insert>, <update>, <delete>, and < Procedure> mapped Statement element. The IBATIS document describes each element in more detail (see Resources for a link to the IBATIS Web site).



Parameter Map and inline parameters

The Parameter Map in the IBATIS framework provides data entry parameters for mapped Statement. Parameter map is not commonly used and is used spontaneously (usually using inline parameters), but listing 4 shows an example of how they work, with a sample Parameter Map and mapped Statement from the document.


Listing 4 The Parameter Map in the IBATIS framework

<parametermap id= "Insert-product-param" class= "Com.domain.Product" >

javatype= "int" nullvalue= " -9999999"/>

Nullvalue= "No_entry"/>
</parameterMap>

<statement id= "insertproduct" parametermap= "Insert-product-param" >
Insert into PRODUCT (prd_id, Prd_description) VALUES (?,?);
</statement>

As you can see, the mapped Statement in Listing 4 refers to the Parameter Map by name, which contains two placeholder question marks. (You will recognize these placeholders, in the form of standard placeholders for JDBC PreparedStatement.) It applies the values obtained from the Parameter Map to these placeholders in the order in which they are defined.

The Parameter map in Listing 4 defines the id attribute getId () of the Com.domain.Product class, mapping it to the first placeholder (question mark) of any mapped Statement that uses this Parameter map. It continues (using the next parameter element) to declare the Description property getdescription () of the Com.domain.Product class, mapping it to the second placeholder in any mapped Statement that uses the Parameter map Character (question mark). In Parametermap, the parameter elements are displayed in the same order as the placeholder question marks that apply them to the mapped Statement that use Parametermap.

It is more common to use inline parameters to map input parameters (see listing 5).


Listing 5. Inline Parameters

<statement id= "insertproduct" parameterclass= "Com.domain.Product" >
Insert into PRODUCT (prd_id, prd_description)
VALUES (#id #, #description #);
</statement>

This syntax replaces #id # with the value returned by GetId () in the Com.domain.Product class, and #description # is replaced by the value returned by the GetDescription () of the Com.domain.Product class. You can view the IBATIS document to find out how to specify a null value.



Result Map

The result map is similar to the Parameter map, but it is used for output. The result map allows you to define how mapped statements (usually some queries) are mapped back to Java objects. Listing 6 provides a quick view of an example from a IBATIS document.


Listing 6. Result Map

<resultmap id= "Get-product-result" class= "Com.domain.Product" >
<result property= "id" column= "prd_id"/>
<result property= "description" column= "Prd_description"/>
</resultMap>

<statement id= "getproduct" resultmap= "Get-product-result" >
SELECT * FROM PRODUCT
</statement>

You can see that the mapped Statement with the GetProduct ID explicitly references the authorization get-product-result of the result map, telling mapped Statement to map prd_id database columns to The Java ID property of the Com.domain.Product class, and also declares the Prd_description database column to be mapped to the Java DESCRIPTION property of the Com.domain.Product class.

I always like to specify the specific columns I'm going to choose, rather than using (for example) select * from.



TransactionManager

The TransactionManager element in the Data Mapper framework allows the transaction service to be configured as you wish, given the configuration. The current supported type for this element is: The JDBC-JDBC transaction manager internal control transactions through the commit () and rollback () methods of the Java.sql.Connection interface. JTA-Uses a global Java Transaction API (JTA) transaction and requires UserTransaction to become available through Java naming and Directory Interface (JNDI) or any other method. EXTERNAL-users can manage their own transactions. This is a good choice for non-transactional data that you have to manage all transactions in any way.

The 3rd part of this tutorial series will look at these transactions in more detail.

Configuring Derby and IBATIS

This section describes everything you need to do to set up basic Derby and IBATIS configurations and make them run. (As mentioned earlier, this tutorial introduces the data Mapper framework and saves the data Access Object configuration for part 2nd.) )

JAR file

The most important thing about putting Apache Derby and IBATIS together is to reduce dependencies. What you need here is the Derby.jar file running Derby, and the Ibatis-common-2.jar and Ibatis-sqlmap-2.jar files. (If you are using the DAO framework, you will need to ibatis-dao-2.jar the file, but the file is not covered in this tutorial.) )

Note that if you want to take advantage of some of the extra features of IBATIS, such as byte code enhancements or centralized/distributed caching, you will also need to include libraries used by IBATIS (Cglib and OS cache, respectively). These additional components are usually unnecessary.



Configuration file

IBATIS rarely asks for configuration files to be set up and run them. The Data Mapper Framework requires an XML configuration file (often called a sql-map-config.xml) that defines the items related to transaction management and how to connect to the database. The list of. xml files that contains items such as mapped statements, result Map, and so on is also here. Take a quick look at the Sql-map-config.xml file that will be used in the simple example in this tutorial (see Listing 7).


Listing 7. Sql-map-config.xml

<! DOCTYPE Sqlmapconfig Public
"-//ibatis.apache.org//dtd SQL Map Config 2.0//en"
"Http://ibatis.apache.org/dtd/sql-map-config-2.dtd" >

<sqlMapConfig>

<properties resource= "Properties/database.properties"/>

<settings cachemodelsenabled= "true" enhancementenabled= "false"
maxsessions= "maxtransactions=" "8" maxrequests= "128"/>

<transactionmanager type= "JDBC" >
<datasource type= "Simple" >
<property value= "${driver}" Name= JDBC. Driver "/>
<property value= "${url}" Name= JDBC. Connectionurl "/>
<property value= "${username}" Name= JDBC. Username "/>
<property value= "${password}" Name= JDBC. Password "/>
<property value= "name=" Pool.maximumactiveconnections "/>"
<property value= "name=" Pool.maximumidleconnections "/>"
<property value= "1000" name= "pool.maximumwait"/>
</dataSource>
</transactionManager>

<sqlmap resource= "Net/humandoing/invoicing/domain/sql/sequence.xml"/>
<sqlmap resource= "Net/humandoing/invoicing/domain/sql/product.xml"/>
</sqlMapConfig>

In Listing 7, there is only one. xml file that describes the mapping, where the file is product.xml. Typically, this information is defined in several files, and then each domain object is roughly divided into an. xml file. Also, note how the XML file refers to the database properties file, which contains information about how to connect to the database. Listing 8 shows a sample database.properties file.


Listing 8. A database.properties file

####################################
# Database Connectivity Properties
####################################

Driver=org.apache.derby.jdbc.embeddeddriver
Url=jdbc:derby:c:/temp/ibatis
Username=
password=

Here, only the fully qualified name of the IBATIS embedded Derby driver and a valid JDBC URL are provided. You do not need to specify a username and password because security is not involved in this example.

In addition to the configuration file in Listing 7, the only thing the Data Mapper framework needs is any one of the. xml files defined to describe the database query and how the object and the database are mapped. The next section discusses the Product.xml file for the sample application.

Although not used in this tutorial, the DAO framework still requires a simple. XML configuration file (often called Dao.xml) and contains a list of items similar to those in the Data Mapper configuration. This section contains a list of transaction management information and a pair of DAO interfaces and implementations (part 2nd of this tutorial series discusses these in more detail).



Set IBATIS for Derby

Because the embedded mode of Derby is used and IBATIS abstracts all database accesses, it is only necessary to provide IBATIS to the correct driver and the correct database URL. IBATIS starts the database, and then provides access to the database in any database-specific calls to the IBATIS framework.

After you complete this simple setup, you are ready to build a simple sample application using the Data Mapper framework.

Test Derby and IBATIS

When you complete the operations in part 1th of this tutorial series, you will use the Jpetstore application in parts 2nd and 3rd. The Jpetstore application is an example IBATIS application that can be downloaded from the IBATIS framework. If you want to get some extra knowledge or want to know about IBATIS, download it from the IBATIS Web site (see Resources for a link).

Now that you've learned some of IBATIS's basics and some of its concepts, you can use it in a small example. In this section, you create a simple Product class and a Sequence class. You can use the Sequence class as the primary key generator that defines the unique key for a product. The next step is to take you through a sample component to see the sample components, and at the end of this section, assemble the sample components together.

Defining objects

First, define the Java objects that you want to use for data all the time. There is nothing special about this, because IBATIS does not require extending any superclass or implementing any interfaces. Listing 9 defines the Sequence class.


Listing 9. Sequence class

public class Sequence {
Private String Sequencename;
private int NextID;

Public Sequence (String sequencename, int nextid) {
This.nextid = NextID;
This.sequencename = Sequencename;
}

Public Sequence () {
}

public int Getnextid () {
return NextID;
}

public void Setnextid (int nextid) {
This.nextid = NextID;
}

Public String Getsequencename () {
return sequencename;
}

public void Setsequencename (String sequencename) {
This.sequencename = Sequencename;
}
}

Listing 10 shows the Product class.


listing 10. Product class

public class Product {
private int productId;
Private String ProductName;
Private String Productdesc;
private int quantity;

Public Product (int productId, String productName,
String Productdesc,int quantity) {
This.productdesc = Productdesc;
This.productid = productId;
This.productname = ProductName;
this.quantity = quantity;
}

Public Product () {
}

public int GetProductID () {
return productId;
}

public void Setproductid (int productId) {
This.productid = productId;
}

Public String Getproductname () {
return productName;
}

public void Setproductname (String productName) {
This.productname = ProductName;
}
//...
}

As you can see, these two classes are just ordinary JavaBeans with getter/setter methods and a few members. Because you want these classes to be mapped to some of the tables in the database, you now have to define some database tables.



Defining tables

You need a table to store the product, and another table from which to get the product and add the product sequence, which can be used as a primary key. Listing 11 shows the data model that Derby is very friendly to maintain for you.


listing 11. Data Model

CREATE TABLE SEQUENCE
(
Sequence_name VARCHAR () not NULL,
next_id INTEGER not NULL,
CONSTRAINT seq_pk PRIMARY KEY (sequence_name)
);

CREATE TABLE PRODUCT (
product_id INTEGER,
Product_Name VARCHAR (128),
Product_desc VARCHAR (512),
QUANTITY INTEGER,
CONSTRAINT prod_pk PRIMARY KEY (product_id)
);


INSERT into SEQUENCE (Sequence_name, next_id)
VALUES (' Productseq ', 1000);

Now you have a SEQUENCE table from which you can select a product and add a sequence of products to produce a primary key for the product table. You have inserted a row in the SEQUENCE table and will begin the operation from product sequence 1000. You also have a product table that contains a few columns that describe some of the typical properties of a product (but do not contain all attributes).



Create SQL Map

Now you need to create a SQL Map that describes the database operations that you want to perform on the Product and Sequence objects. These database operations typically include inserts, queries, updates, and deletes.

Listing 12 shows the SQL Map for the Product class.


listing 12. SQL Map for the Product class

<! DOCTYPE sqlmap Public "-//ibatis.apache.org//dtd SQL Map 2.0//en"
"Http://ibatis.apache.org/dtd/sql-map-2.dtd" >

<sqlmap namespace= "Product" >

<typealias alias= "Product"
Type= "Net.humandoing.invoicing.domain.Product"/>

<resultmap id= "Productresult" class= "Product" >
<result property= "ProductId" column= "product_id"/>
<result property= "ProductName" column= "Product_Name"/>
<result property= "Productdesc" column= "Product_desc"/>
<result property= "Quantity" column= "Quantity"/>
</resultMap>

<update id= "updateproduct" parameterclass= "Product" >
Update PRODUCT Set product_name = #productName #,
Product_desc = #productDesc #,
QUANTITY = #quantity # where
product_id = #productId #
</update>

<select id= "getproduct" resultmap= "Productresult"
parameterclass= "Product" >
Select product_id, Product_Name, Product_desc, QUANTITY
From PRODUCT where product_id = #productId #
</select>

<insert id= "insertproduct" parameterclass= "Product" >
Insert into PRODUCT (product_id, Product_Name, Product_desc, quantity)
VALUES (#productId #, #productName #, #productDesc #, #quantity #)
</insert>

</sqlMap>

Note the Typealias element. It only allows a class to be referenced through a shorter alias (in this case, product) rather than a fully qualified class name.

In Listing 12 You can also see a RESULTMAP element that describes how you want to map ResultSet to the Product object by executing a query. This special Resultmap maps the product_id columns in the database to the ProductId property of the product class, maps the Product_Name columns in the database to the ProductName property of the product class, and so on.

Now let's take a quick look at the SQL Map for the Sequence class, as shown in Listing 13.


listing 13. SQL Map for the Sequence class

<?xml version= "1.0" encoding= "UTF-8" standalone= "no"?>
<! DOCTYPE sqlmap Public "-//ibatis.com//dtd SQL Map 2.0//en"
"Http://www.ibatis.com/dtd/sql-map-2.dtd" >

<sqlmap namespace= "Sequence" >

<typealias alias= "Sequence"
Type= "Net.humandoing.invoicing.domain.Sequence"/>

<resultmap id= "Sequenceresult" class= "sequence" >
<result property= "Sequencename" column= "Sequence_name"/><

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.