New features within iBATIS 3

sponsored links
New features within iBATIS 3

iBatis has been renamed MyBatis

Introduction: iBATIS is a project, mainly for data access objects (data access object, DAO), and object-relational mapping (object-relational mapping, ORM). You can use it to easily handle Java? Objects and databases. On the iBATIS 3 beta 9 update in the January 23, 2010 release. iBATIS iBATIS 3 is a complete rewrite of version and includes some significant updates. This article describes some of the iBATIS 3 new features.

If you write Java code, time is not short, you may recall that some days: You write a lot of the class that contains logic methods, these methods will be the data in Java objects mapped to relational database management system (RDBMS) of data or data from the RDBMS in Java objects mapped to the data. Now, for the most part, this manual intervention is not encouraged, but recommend that you use ORM tools as a best practice.

ORM tool allows you to configure the data elements within a relational database and the mapping between Java object properties. Configured, these tools allow you to feel at ease to use Java objects, Java classes without having to worry about the properties of how the data is stored or how to retrieve, thus bringing you from a lot of duplicate code writing, debugging and error handling in the liberation of out.

This article describes the new features within iBATIS 3, iBATIS 3 from the Apache Foundation is an ORM tool can be used to connect to the database to build Java applications. To maximize the use of this article, it is recommended to use Java Development Kit (JDK) V5 or later; Eclipse V3.4 or later. This article uses iBATIS 3 beta 9. iBATIS site that is very close to the generic version beta 9 (GA), so in the GA version is available, the examples in this article shall also apply to GA version.

The main purpose of the iBATIS to map to the RDBMS, so also need a database in order to obtain a complete picture of these examples. This example in this article chose to use Apache Derby as the database. One thing is worth noting that, in addition to writing you from using the Java Database Connectivity (JDBC) Java code duplication freed, ORM tool, another advantage is to provide better data layer abstraction. Only minor changes to the configuration iBATIS and JDBC database to be the correct reference, you can be the example in this article for other databases.

iBATIS Overview

iBATIS 3 is a persistence framework that can be used to configure the Java class properties and listed within the RDBMS mapping between. At configuration time, this framework is responsible for handling JDBC connections and distribution. You can use XML file configuration iBATIS 3. from the iBATIS iBATIS site (see Resources) to compressed archives (ZIP) format for download. Within this archive is a Java Archive (JAR) file, which can be included in the Java object to provide the required classes.

As shown in Listing 1 is a sample application in the use of Java classes.

Listing 1. The sample application used in
Automobile
Class

package com.ibm.developerWorks.examples.ibatis.model;
public class Automobile {
private int id;
private String make;
private String model;
private int year;
public Automobile () {
super ();
)
public Automobile (final int id, final String make, final String model,
final int year) {
super ();
this.id = id;
this.make = make;
this.model = model;
this.year = year;
)
public int getId () {
return id;
)
public String getMake () {
return make;
)
public String getModel () {
return model;
)
public int getYear () {
return year;
)
public void setId (final int id) {
this.id = id;
)
public void setMake (final String make) {
this.make = make;
)
public void setModel (final String model) {
this.model = model;
)
public void setYear (final int year) {
this.year = year;
)
@ Override
public String toString () {
return "Automobile [id =" + id + ", make =" + make + ", model =" + model + ",
year = "+ year +"] ";
)
)

This
Automobile
Class is a simple Java object (plain old Java object, POJO), contains the data used by the application. iBATIS framework for this object in the configuration can persist after the database or as a method (used to select the object from the database) the results back to this object.

Listing 2 shows this SQL script to create a sample database table.

Listing 2. To create automobiles table SQL scripts

CREATE TABLE automobiles (
id INT NOT NULL,
make VARCHAR (255) NOT NULL,
model VARCHAR (255) NOT NULL,
model_year INT NOT NULL
);

Will be able to execute the database scripts to create the table in the database. If you are using Derby as a database, you can use Derby included in the bin folder of the command-line utility to run this script (see Listing 3). Before running this example, make sure that
DERBY_HOME
Variable designated as the Derby to install the full path to that directory and the SQL script is saved to a document called create.sql.

Listing 3. Use the Derby ij tool to run command-line create.sql

$ Cd $ DERBY_HOME / bin
$. / Ij
> Connect 'jdbc: derby: / tmp / MyDB';
> Run create.sql

Shown in Listing 4 in the XML mapping file allows you to map Java classes to the data within the attribute data table column.

Listing 4. XML mapping file (automobile-mapper.xml)

<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE mapper
PUBLIC "- / / ibatis.apache.org / / DTD Mapper 3.0 / / EN"
"Http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.ibm.developerWorks.examples.ibatis.model.Automobile">
<resultMap type="Automobile">
<result column="id" property="id" />
<result column="make" property="make" />
<result column="model" property="model" />
<result column="model_year" property="year" />
</ ResultMap>
<Select parameterType = "int" resultType = "Automobile"
resultMap = "automobileResult">
select * from
automobiles where id = # {id}
</ Select>
<insert parameterType="Automobile">
insert into automobiles (id,
model, make, model_year)
values (# {id}, # {model}, # {make}, # {year})
</ Insert>
<delete parameterType="int">
delete from automobiles where
id = # {id}
</ Delete>
<delete>
delete from automobiles
</ Delete>
</ Mapper>

The XML mapping file that contains
<select>
,
<insert>
And
<delete>
Elements, three elements contained within the code looks like a conventional ANSI SQL. The XML element name corresponds to the type of SQL statement -
<insert>
Element corresponds to the SQL
INSERT
Statement, and so on. Parameters in the SQL code within the
# {Parameter}
Definition, which parameter is the Java class name of the field. For example,
Automobile
Object has a name
make
The field, so you can use
# {Make}
The value stored in this field is passed to the SQL statement.

iBATIS 3 A new feature is the use of annotations in the Java interface, to perform the same configuration. I will later on how to use Java 5 annotations instead of XML configuration files (see the Java 5 features.)

Finally, Listing 5 shows this iBATIS 3 XML configuration file, which specifies the name of the database, the driver you want to use some data types and other properties, such as certificates. Mapping file name, such as the name as shown in Listing 4 is the configuration file
<mappers>
Elements listed.

Listing 5. XML configuration files (ibatis-config.xml)

<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE configuration
PUBLIC "- / / ibatis.apache.org / / DTD Config 3.0 / / EN"
"Http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<configuration>
<typeAliases>
<TypeAlias type = "com.ibm.developerWorks.examples.ibatis.model.Automobile"
alias = "Automobile" />
</ TypeAliases>
<environments default="development">
<environment>
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<Property name = "driver"
value = "org.apache.derby.jdbc.EmbeddedDriver" />
<property name="url" value="jdbc:derby:/tmp/MyDB" />
</ DataSource>
</ Environment>
</ Environments>
<mappers>
<mapper resource="automobile-mapper.xml" />
</ Mappers>
</ Configuration>

If you use Java annotations to define the method of mapping between objects and the database, you will not need this configuration file, because iBATIS 3 provides a Java application programming interface (API), allowing you to programmatically complete the configuration.

One advantage of using the iBATIS XML configuration it could be a good can be used to map objects to relational databases of existing ORM framework. With
Mapper
Class and mapping file, the focus becomes the object is mapped to existing data structures, not to make a data structure to comply with the structure of the object. Although the configuration cost than enables developers to use a more independent of the data structure of the framework more often, but a separate database and object model design does have its own advantages. Excellent relational database and object model designer who may have competing goals, which makes the realization of their own also have great differences.

In the past, I have a lot in the project used iBATIS, these projects use the relationship between the database structure and stored procedures, and the design of the database developers have little control.

To test the examples in this article, you need to create an empty Java project. In this new Java project, create an include
main ()
Methods class, as shown in Listing 6.

Listing 6.
Main
Class

package com.ibm.developerWorks.examples.ibatis;
import java.io.IOException;
import javax.sql.DataSource;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.derby.jdbc.EmbeddedDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import com.ibm.developerWorks.examples.ibatis.data.AutomobileMapper;
import com.ibm.developerWorks.examples.ibatis.model.Automobile;
public class Main {
private static final String CREATE = "create";
private static final String DELETE = "delete";
private static final String IBATIS_CONFIG = "ibatis-config.xml";
private static final String SHOW = "show";
@ SuppressWarnings ("static-access")
private static Options createOptions () {
Options options = new Options ();
options.addOption (CREATE, false, "creates the objects in the database");
options.addOption (OptionBuilder.withArgName (SHOW). hasArg (). withDescription (
"Shows the specified automobile"). WithLongOpt (SHOW). Create ());
options.addOption (DELETE, false, "deletes all of the objects in database");
return options;
)
private static SqlSessionFactory createSqlMapper () throws IOException {
Reader reader = Resources.getResourceAsReader (IBATIS_CONFIG);
return new SqlSessionFactoryBuilder (). build (reader);
)
public static void main (final String [] args) {
Options options = createOptions ();
try (
CommandLine cmd = new GnuParser (). Parse (options, args);
SqlSession session = createSqlMapper (). OpenSession ();
try (
if (cmd.hasOption (CREATE)) {
System.out.println ("Creating the objects in the database ...");
/ / Create the automobiles
session.insert (Automobile.class.getName () + ". insert", new
Automobile (1, "Toyota", "Tercel", 1993));
session.insert (Automobile.class.getName () + ". insert", new
Automobile (2, "Honda", "CR-V", 2000));
session.insert (Automobile.class.getName () + ". insert", new
Automobile (3, "Chevrolet", "Impala", 1964));
session.insert (Automobile.class.getName () + ". insert", new
Automobile (4, "Dodge", "Pickup", 1946));
session.commit ();
} Else if (cmd.hasOption (SHOW)) {
Automobile auto = (Automobile) session.selectOne (
Automobile.class.getName () + ". Select", cmd.getOptionValue (SHOW));
if (auto == null) {
System.out.println ("No matching results found!");
) Else (
System.out.println (auto);
)
} Else if (cmd.hasOption (DELETE)) {
session.delete (Automobile.class.getName () + ". deleteAll");
session.commit ();
) Else (
System.out.println ("Doing nothing.");
)
) Finally (
session.close ();
)
) Catch (Exception e) (
e.printStackTrace ();
)
)
)

In order to avoid arbitrary argument parsing code
main
Method uses the Apache Commons CLI to parse the command line program to send it to these arguments. Apache Commons CLI project can make use of this example to respond to different command-line arguments, such as
- Create
,
- Delete
Or
- Show
. Apache Commons CLI project on more information, see the reference information. The support of the argument that
main ()
Method can be involved in some examples of objects and iBATIS operation.

This example uses the iBATIS
Resources
Class to load the configuration from an XML file.
Resources
Class file as a
Reader
And pass it to load
SqlSessionFactoryBuilder
.
SqlSessionFactoryBuilder
To construct a
SqlSessionFactory
, Which in turn is used to create these
SqlSession
Object, so that your code can be mapped within the definition of class methods and database interaction.

Compile and run the sample code, you need to import iBATIS 3, Apache Commons CLI and Apache Derby JAR files (ibatis-3-core-x.jar, commons-cli-1.2.jar and derby.jar).

Running through the main class from Eclipse, you can run this example the. If you want to add arguments to the Java call, you can open the Run> Run Configurations and locate the Java Application / Main run configuration. In the Arguments tab, specify you want the Program Arguments (Figure 1) provided arguments.

Figure 1. Adding to the argument of the running configuration

Of course, you can also call the Java application from the command line, but please remember to set the classpath to include the iBATIS 3, Apache Commons CLI and Apache Derby JAR files. For an example of how the calling application, can be found in Listing 7.

Listing 7. Run the application from the command line

$ Java-classpath {jars} com.ibm.developerWorks.examples.ibatis.Main - create
Creating the objects in the database ...

In the implementation of the Java application, you can see
- Create
Created four new
Automobile
Objects and add them to the database automobiles table. Use
- Delete
Argument can remove these objects from the database. Use with ID,
- Show
Run the SQL script for database record matching to create a data
Automobile
Object and displays the results to the console.

XML configuration example to work, you can begin to understand another key iBATIS 3 new features: Java annotations support.

iBATIS 3 brings some new changes, allowing you to use Java 5 annotations. By using annotations, you can create a mapper interface to the Java code for your object to the database from within the entire map. The code shown in Listing 8 shows this for the configuration (not the XML configuration)
AutomobileMapper
Interface.

Listing 8.
AutomobileMapper
Interface

package com.ibm.developerWorks.examples.ibatis.data;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import com.ibm.developerWorks.examples.ibatis.model.Automobile;
public interface AutomobileMapper {
@ Select ("select id, make, model, model_year as \" year \ "from automobiles
where id = # {id} ")
Automobile selectAutomobile (final int id);
@ Insert ("insert into automobiles (id, make, model, model_year)
values (# {id}, # {make}, # {model}, # {year}) ")
void insertAutomobile (final Automobile arg);
@ Delete ("delete from automobiles")
void deleteAll ();
)

In
Automobile
mapper's XML configuration,
resultMap
Element is used to map
model_year
Database column
Automobile
Object on the
year
Field. This map is quite simple, you can within the comment, just use the SQL alias for the column properties conferred on it, this feature may be in the
@ Select
Completed within the definition of the SQL annotation.

AutomobileMapper
In the interface
Select
Note the
selectAutomobile
Method is mapped to the given value to the table to select a record from the automobiles of the SQL. This value is specified as argument
id
Parameters was as
# {Id}
Within SQL statements included in this, as it did in the XML configuration. Using the Java interface to map the SQL method has the advantage of a great feedbac compile-time error will appear in the Java editor. In this way, we can confirm that these methods can return the correct type, and XML configuration typically need to execute code to find errors.

In addition, iBATIS 3 now supports interface inheritance, which allows optimization of Java interfaces to reduce code duplication.

iBATIS documentation such as a reminder that for the small and relatively simple projects, comments can be more simple and easy to read. However, more XML configuration, the comments function is relatively limited. If the project contains a complex object or a complex database structure, consider using XML configuration instead of Java annotations.

iBATIS configuration requirements based on an instance of annotation also slightly different. We no longer use
Reader
Class to read XML configuration, but would like to
Configuration
Add object mapping programs, such as shown in Listing 9.

Listing 9. Using the new Java code annotation configuration

package com.ibm.developerWorks.examples.ibatis;
/ / Snipped imports
public class Main {
/ / Snipped constants declarations - didn't change
/ / New method for creating data source
private static DataSource createDataSource () {EmbeddedDataSource
dataSource = new org.apache.derby.jdbc.EmbeddedDataSource ();
dataSource.setDatabaseName ("/ tmp / MyDB"); return dataSource;}
@ SuppressWarnings ("static-access")
private static Options createOptions () {
/ / Snipped ... no changes
)
private static SqlSessionFactory createSqlMapper () throws
IOException {DataSource datasource = createDataSource ();
TransactionFactory transaction = new JdbcTransactionFactory ();
Configuration configuration = new Configuration (new Environment
("Development", transaction, datasource)); configuration
. AddMapper (AutomobileMapper.class);
return new SqlSessionFactoryBuilder (). build (configuration);
)
public static void main (final String [] args) {
Options options = createOptions ();
try (
CommandLine cmd = new GnuParser (). Parse (options, args);
SqlSession session = createSqlMapper (). OpenSession ();
AutomobileMapper mapper = session.getMapper (AutomobileMapper.class);
try (
if (cmd.hasOption (CREATE)) {
System.out.println ("Creating the objects in the database ...");
/ / Create the automobiles
mapper.insertAutomobile (new Automobile
(1, "Toyota", "Tercel", 1993));
mapper.insertAutomobile (new Automobile
(2, "Honda", "CR-V", 2000));
mapper.insertAutomobile (new Automobile (3,
"Chevrolet", "Impala", 1964));
mapper.insertAutomobile (new Automobile (4, "Dodge", "Pickup", 1946));
session.commit ();
} Else if (cmd.hasOption (SHOW)) {
Automobile auto = mapper.selectAutomobile (Integer.parseInt (cmd.getOptionValue (SHOW)));
if (auto == null) {
System.out.println ("No matching results found!");
) Else (
System.out.println (auto);
)
} Else if (cmd.hasOption (DELETE)) {
mapper.deleteAll ();
session.commit ();
) Else (
System.out.println ("Doing nothing.");
)
) Finally (
session.close ();
)
) Catch (Exception e) (
e.printStackTrace ();
)
)
)

Provide
addMapper ()
Methods
AutomobileMapper
Is shown in Listing 8, the same Java interface.

Configuration
Objects also need to
DataSource
Achieved. In this case,
DataSource
Implementation is in the static
createDataSource ()
Method easily created. However, in a production application, should be modified to make the data of source information - such as database name - more dynamic. If you are responsible for the management of a persistent application server or Web server to build applications, you can use the Java Naming and Directory Interface (JNDI) to obtain
DataSource
.

iBATIS Schema Migrations System (iBATIS migration) project is not used to the older model XML configuration to the new model projects. Instead, the project aims at the development of the database as the database changes from one version to another version of simplifying the migration of database changes. You can use this tool to build applications for you automatically change the SQL script, which can greatly reduce errors.

ORM iBATIS 3 is a durable framework for the Java object is mapped to the properties listed within the database. iBATIS to map as the central focus of a good object model mapped with a good relational database design.

iBATIS 3 A new feature is the use of Java annotations to map, making the map more clean and more intuitive, and can be in the form of Java source code for many items. iBATIS 3 also provides an object using the XML configuration file mapping feature. The existence of this dual configuration allows you to choose for your project configuration iBATIS most simple way.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of New features within iBATIS 3

  • hibernate Technical Study Notes (first)

    Introduction: Model does not match (impedance mismatch) java object-oriented language, object model, its key concepts are: inheritance, association, polymorphism, etc.; database is the relational model, its key concepts are: tables, primary keys, for ...

  • Choose Hibernate or iBATIS has its reasons

    Hibernate features: Hibernate powerful database has nothing to do with good, O / R mapping ability, and if you are very proficient in Hibernate, but also for Hibernate to conduct an appropriate package, then your project will be the entire persistence lay

  • Hibernate Inteceptor

    The end of the project stage, the client suddenly put forward a very troublesome but normal demand, the system records all changes must be carried out. Formats such as: 2004.1.1 12:30 Ikuya wind orders Sales Order Date 2004.1.2-> 2004.1.3 The firs ...

  • JDBC driver types

    1, JDBC is a included in the J2SE and J2EE platform API, you have access to a variety of data sources, in particular, are so typical as Oracle relational database management system. Sun Microsystems Inc. in January 1997 the introduction of JDBC techn ...

  • FLEX: integrating Spring + Hibernate

    Before a friend also wanted to study development of FLEX. Asked me to help him to be a small sample. Spent a weekend time, to integrate a sampleproject. Client: FLEX Server: Spring2.5 + Hibernate3.2 + Hibernate-annotations3.3.1 + MySQL5 FDS: BlazeDS3 IDE:

  • Learn Java flow

    Related Articles: J2EE without EJB Introducing to Spring Framework (English revised edition) J2EE without EJB caused consider Recommend circles: reading space More related recommend Java Learning Path (1), tools, articles First, JDK (Java Development Kit)

  • The level Hibernate cache

    Hibernate cache level: (1) a cache is very short and the session life cycle consistent, also known as session-level cache-level cache or transaction-level cache (2) Ways of Supporting level cache: get (); load (); iterator (); only entity object cach ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries