DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Trending

  • What’s Got Me Interested in OpenTelemetry—And Pursuing Certification
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • Proactive Security in Distributed Systems: A Developer’s Approach
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. IBatis (MyBatis): Handling Constructors

IBatis (MyBatis): Handling Constructors

By 
Loiane Groner user avatar
Loiane Groner
·
Mar. 12, 11 · Interview
Likes (0)
Comment
Save
Tweet
Share
19.3K Views

Join the DZone community and get the full member experience.

Join For Free

this tutorial will walk you through how to setup  ibatis  (  mybatis  ) in a simple java project and will present an example using a class constructor with arguments.

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 the script into your database before getting started with the project implementation. you will find the script (with dummy data) inside the sql folder.

1 – pojo

i represented the beans here with a uml model, but you can download the complete source code in the end of this article.

as you can see, we do not have a default construtor in this class, only a constructor with some arguments. some persistence frameworks requires a default constructor, but you have to be careful with your business logic.

let’s say there are a couple of mandatory atributes in your class. nothing is going to stop you if you do not set these atributes and try to insert, update on the database. and you problably will get an exception for that.

to prevent this kind of situation, you can create a constructor with the mandatory arguments. and ibatis/  mybatis  can handle this situation for you, because you do not need to create a default constructor.

2 – blog mapper – xml

while properties will work for most data transfer object (dto) type classes, and likely most of yourdomain model, there may be some cases where you want to use immutable classes. often tables thatcontain reference or lookup data that rarely or never changes is suited to immutable classes.constructor injection allows you to set values on a class upon instantiation, without exposing publicmethods. mybatis also supports private properties and private javabeans properties to achieve this, butsome people prefer constructor injection. the constructor element enables this.
in order to inject the results into the constructor, mybatis needs to identify the constructor by the type of its parameters. java has no way to introspect (or reflect) on parameter names. so when creating a constructor element, ensure that the arguments are in order, and that the data types are specified.

if you need, you can still map another attributes, such as association, collection in your resultmap.

following is the blog.xml file:

<?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="blog">
 
    <resultmap id="resultblog" type="blog">
        <constructor>
            <idarg column="id" javatype="int"/>
            <arg column="url" javatype="string"/>
        </constructor>
        <result property="name"/>
    </resultmap>
 
    <select id="selectblog" resultmap="resultblog">
        select idblog as id, name, url from blog
    </select>
 
</mapper>

3 - blog mapper – annotations

we did the configuration in xml, now let’s try to use annotations to do the same thing we did using xml.

this is the code for blogmapper.java:

package com.loiane.data;
 
import java.util.list;
 
import org.apache.ibatis.annotations.arg;
import org.apache.ibatis.annotations.constructorargs;
import org.apache.ibatis.annotations.select;
 
import com.loiane.model.blog;
 
public interface blogmapper {
 
    /**
     * returns the list of all blog instances from the database.
     * @return the list of all blog instances from the database.
     */
    @select("select idblog as id, name, url from blog ")
    @constructorargs(value = {
        @arg(column="id",javatype=integer.class),
        @arg(column="url",javatype=string.class)
    })
    list<blog> selectallblogs();
}

let’s take a look at the @constructorargs and @arg annotations:

@constructorargs

collects a group of results to be passed to a result object constructor.

attributes: value, which is an array of args.

xml equivalent: constructor

@arg

a single constructor argument that is part of a constructorargs collection.

attributes: id, column, javatype, jdbctype, typehandler.

the id attribute is a boolean value that identifies the property to be used for comparisons, similar to the <idarg> xml element.

xml equivalent: idarg, arg

we do not need to use the @results annotation because the other attributes has the same name, so mybatis knows how to map them.

download

if you want to download the complete sample project, you can get it from my github account:  https://github.com/loiane/ibatis-constructor 

if you want to download the zip file of the project, just click on download:

there are more articles about ibatis to come. stay tooned!

happy coding! :)

once again though, some may find this external definition of maps somewhat tedious. thereforethere’s an alternative syntax for those that prefer a more concise mapping style.

MyBatis

Opinions expressed by DZone contributors are their own.

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!