Getting Started with iBatis (MyBatis): XML Configuration
This tutorial will walk you through how to setup iBatis (MyBatis) in a simple Java project and will present examples using simple insert, update, select and delete statements.
Join the DZone community and get the full member experience.
Join For Freethis tutorial will walk you through how to setup ibatis ( mybatis ) in a simple java project and will present examples using simple insert, update, select and delete statements.
pre-requisites
for this tutorial i am using:
ide
:
eclipse
(you can use your favorite one)
database
:
mysql
libs/jars
:
mybatis
,
mysql
conector and
junit
(for testing)
this is how your project should look like:
sample database
please run this script into your database before getting started with the project implementation:
drop table if exists `blog`.`contact`;create table `blog`.`contact` ( `contact_id` int(11) not null auto_increment, `contact_email` varchar(255) not null, `contact_name` varchar(255) not null, `contact_phone` varchar(255) not null, primary key (`contact_id`))engine=innodb; insert into contact (contact_name, contact_phone, contact_email) values ('contact0','(000) 000-0000', 'contact0@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact1', '(000) 000-0000', 'contact1@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact2', '(000) 000-0000', 'contact2@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact3', '(000) 000-0000', 'contact3@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact4', '(000) 000-0000', 'contact4@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact5', '(000) 000-0000', 'contact5@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact6', '(000) 000-0000', 'contact6@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact7', '(000) 000-0000', 'contact7@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact8', '(000) 000-0000', 'contact8@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact9', '(000) 000-0000', 'contact9@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact10', '(000) 000-0000', 'contact10@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact11', '(000) 000-0000', 'contact11@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact12', '(000) 000-0000', 'contact12@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact13', '(000) 000-0000', 'contact13@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact14', '(000) 000-0000', 'contact14@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact15', '(000) 000-0000', 'contact15@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact16', '(000) 000-0000', 'contact16@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact17', '(000) 000-0000', 'contact17@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact18', '(000) 000-0000', 'contact18@loianetest.com');insert into contact (contact_name, contact_phone, contact_email) values ('contact19', '(000) 000-0000', 'contact19@loianetest.com');
1 – contact pojo
we will create a pojo class first to respresent a contact with id, name, phone number and email address:
package com.loiane.model; public class contact { private int id; private string name; private string phone; private string email; public contact(int id, string name, string phone, string email) { super(); this.id = id; this.name = name; this.phone = phone; this.email = email; } public contact() {} //getters and setters}
2 – contact.xml
this is the ibatis/mybatis sql map configuration file for contact class. we are going to write all the sql queries, map a query to object in this file – here is where all the magic happens!
<?xml version="1.0" encoding="utf-8"?><!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="contact"> <resultmap id="result" type="contact"> <result property="id" column="contact_id"/> <result property="name" column="contact_name"/> <result property="phone" column="contact_phone"/> <result property="email" column="contact_email"/> </resultmap> <select id="getall" resultmap="result"> select * from contact </select> <select id="getbyid" parametertype="int" resultmap="result"> select * from contact where contact_id = #{id} </select> <delete id="deletebyid" parametertype="int"> delete from contact where contact_id = #{id}; </delete> <insert id="insert" parametertype="contact"> insert into contact (contact_email, contact_name, contact_phone) values (#{name}, #{phone}, #{email}); <selectkey keyproperty="id" resulttype="int" order="after"> select last_insert_id() as id </selectkey> </insert> <update id="update" parametertype="contact"> update contact set contact_email = #{email}, contact_name = #{name}, contact_phone = #{phone} where contact_id = #{id}; </update> </mapper>
what this file contains:
- resultmap – the most complicated and powerful element that describes how to load your objects from the database result sets.
- insert – a mapped insert statement.
- update – a mapped update statement.
- delete – a mapped deleete statement.
- select – a mapped select statement.
result map
the resultmap element is the most important and powerful element in mybatis. it’s what allows you to do away with 90% of the code that jdbc requires to retrieve data from resultsets, and in some cases allows you to do things that jdbc does not even support. in fact, to write the equivalent code for something like a join mapping for a complex statement could probably span thousands of lines of code. the design of the resultmaps is such that simple statements don’t require explicit result mappings at all, and more complex statements require no more than is absolutely necessary to describe the relationships.
in this example, the name of the table column is different from the contact class. that is why we have to map the column with the class property. if the column name is the same as the property, you do not need to use the column=”" option in the result map.
and remember that typealiases are your friend. use them so that you don’t have to keep typing the fully qualified path of your class out. – we are going to set it in the mybatis main configuration file.
select statment
the first select statment in this example is called “ getall “, and it means we are going to use this id to call the statment in dao class. the other option we set is the resultmap, which we mapped to contact class, and it means the statment is going to return a list of contacts (list).
the second select statment in this example is called “ getbyid “. we set a option called parameter of type int (or integer) and it returns a object of type contact. notice the parameter notation #{id} . this tells mybatis to create a preparedstatement parameter. with jdbc, such a parameter would be identified by a “?” in sql passed to a new preparedstatement.
delete statment
the delete statment is also very simple. we set a parameter type called id (same thing as getbyid statment) so we can filter what it is going to be deleted.
update statment
in the update statement we ser a parameter of type contact, which means we are going to pass a contact object as parameter to the update method in dao class. note the parameter notation #{name}, #{phone}, #{email} and #{id}. all the parameters must have the same name as contact properties, otherwise mybatis will not be able to map the object-parameters.
insert statment
insert is a little bit more rich in that it has a few extra attributes and sub-elements that allow it to deal with key generation in a number of ways. first, if your database supports auto-generated key fields (e.g. mysql and sql server), then you can simply set usegeneratedkeys=”true” and set the keyproperty to the target property and you’re done.
mybatis has another way to deal with key generation for databases that don’t support auto-generated column types, or perhaps don’t yet support the jdbc driver support for auto-generated keys.
in this example, we are going to set manually the generated id in the object with the selectkey option. in this example, the selectkey would be run after the insert statment and with the last_insert_id () function we will get the last generated key (of type int) and set it to the id property.
3 – mapper configuration file
the mybatis xml configuration file contains settings and properties that have a dramatic effect on how mybatis behaves. the high level structure of the document is as follows:
-
configuration
- properties
- settings
- typealiases
- typehandlers
- objectfactory
- plugins
-
environments
-
environment
- transactionmanager
- datasource
-
environment
- mappers
hint: you have to follow the order above, otherwise you will get an exception.
the sqlmapconfig.xml from our project:
<?xml version="1.0" encoding="utf-8"?><!doctype configuration public "-//mybatis.org//dtd config 3.0//en" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typealiases> <typealias alias="contact" type="com.loiane.model.contact"/> </typealiases> <environments default="development"> <environment id="development"> <transactionmanager type="jdbc"/> <datasource type="pooled"> <property name="driver" value="com.mysql.jdbc.driver"/> <property name="url" value="jdbc:mysql://localhost:3306/blog"/> <property name="username" value="root"/> <property name="password" value="root"/> </datasource> </environment> </environments> <mappers> <mapper resource="com/loiane/data/contact.xml"/> </mappers> </configuration>
let’s take a look at the configuration properties we are using.
type aliases
a type alias is simply a shorter name for a java type. it’s only relevant to the xml configuration and simply exists to reduce redundant typing of fully qualified classnames.
remember we used contact as type in the resultmap property in contact.xml ()? this is a great help!
environments
mybatis can be configured with multiple environments. this helps you to apply your sql maps to multiple databases for any number of reasons. for example, you might have a different configuration for your development, test and production environments. or, you may have multiple production databases that share the same schema, and you’d like to use the same sql maps for both. there are many use cases.
one important thing to remember though: while you can configure multiple environments, you can only choose one per sqlsessionfactory instance.
the default environment and the environment ids are self explanatory. name them whatever you like, just make sure the default matches one of them.
transaction manager
there are two transactionmanager types (i.e. type=”[jdbc|managed]”) that are included with mybatis:
- jdbc – this configuration simply makes use of the jdbc commit and rollback facilities directly. it relies on the connection retrieved from the datasource to manage the scope of the transaction.
- managed – this configuration simply does almost nothing. it never commits, or rolls back a connection. instead, it lets the container manage the full lifecycle of the transaction (e.g. spring or a jee application server context). by default it does close the connection. however, some containers don’t expect this, and thus if you need to stop it from closing the connection, set the closeconnection property to false.
in this example we are going to use jdbc.
data source
the datasource element configures the source of jdbc connection objects using the standard jdbc datasource interface.
- driver – this is the fully qualified java class of the jdbc driver (not of the datasource class if your driver includes one).
- url – this is the jdbc url for your database instance.
- username – the database username to log in with.
- password – the database password to log in with.
4 – mybatisconnectionfactory
every mybatis application centers around an instance of sqlsessionfactory. a sqlsessionfactory instance can be acquired by using the sqlsessionfactorybuilder. sqlsessionfactorybuilder can build a sqlsessionfactory instance from an xml configuration file, of from a custom prepared instance of the configuration class.
package com.loiane.dao; import java.io.filenotfoundexception;import java.io.ioexception;import java.io.reader; import org.apache.ibatis.io.resources;import org.apache.ibatis.session.sqlsessionfactory;import org.apache.ibatis.session.sqlsessionfactorybuilder; public class mybatisconnectionfactory { private static sqlsessionfactory sqlsessionfactory; static { try { string resource = "sqlmapconfig.xml"; reader reader = resources.getresourceasreader(resource); if (sqlsessionfactory == null) { sqlsessionfactory = new sqlsessionfactorybuilder().build(reader); } } catch (filenotfoundexception filenotfoundexception) { filenotfoundexception.printstacktrace(); } catch (ioexception ioexception) { ioexception.printstacktrace(); } } public static sqlsessionfactory getsqlsessionfactory() { return sqlsessionfactory; }}
5 – contactdao
now that we set up everything needed, let’s create our dao. to call the sql statments, we need to call the namespace and the name of the sql statment as follows:
package com.loiane.dao; import java.util.list; import org.apache.ibatis.session.sqlsession;import org.apache.ibatis.session.sqlsessionfactory; import com.loiane.model.contact; public class contactdao { private sqlsessionfactory sqlsessionfactory; public contactdao(){ sqlsessionfactory = mybatisconnectionfactory.getsqlsessionfactory(); } /** * returns the list of all contact instances from the database. * @return the list of all contact instances from the database. */ @suppresswarnings("unchecked") public list<contact> selectall(){ sqlsession session = sqlsessionfactory.opensession(); try { list<contact> list = session.selectlist("contact.getall"); return list; } finally { session.close(); } } /** * returns a contact instance from the database. * @param id primary key value used for lookup. * @return a contact instance with a primary key value equals to pk. null if there is no matching row. */ public contact selectbyid(int id){ sqlsession session = sqlsessionfactory.opensession(); try { contact contact = (contact) session.selectone("contact.getbyid",id); return contact; } finally { session.close(); } } /** * updates an instance of contact in the database. * @param contact the instance to be updated. */ public void update(contact contact){ sqlsession session = sqlsessionfactory.opensession(); try { session.update("contact.update", contact); session.commit(); } finally { session.close(); } } /** * insert an instance of contact into the database. * @param contact the instance to be persisted. */ public void insert(contact contact){ sqlsession session = sqlsessionfactory.opensession(); try { session.insert("contact.insert", contact); session.commit(); } finally { session.close(); } } /** * delete an instance of contact from the database. * @param id primary key value of the instance to be deleted. */ public void delete(int id){ sqlsession session = sqlsessionfactory.opensession(); try { session.delete("contact.deletebyid", id); session.commit(); } finally { session.close(); } }}
download
if you want to learn more about the mybatis configuration options, please read the user guide. you will find everything you need there. all the quoted sentences are from the mybatis 3 user guid. i also used it as reference to implement this sample project.
i also created a testcase class. if you want to download the complete sample project, you can get it from my github account: https://github.com/loiane/ibatis-helloworld
if you want to download the zip file of the project, just click on download:
next articles we are going to explore more ibatis/mybatis options!
from http://loianegroner.com/2011/02/getting-started-with-ibatis-mybatis-xml-configuration/
Opinions expressed by DZone contributors are their own.
Comments