MyBatis

Last updated
MyBatis
Developer(s) The MyBatis team
Stable release
3.5.10 / May 23, 2022;5 days ago (2022-05-23) [1]
Repository
Written in Java
Operating system Cross-platform
Type Persistence framework
License Apache License 2.0
Website www.mybatis.org   OOjs UI icon edit-ltr-progressive.svg

MyBatis is a Java persistence framework that couples objects with stored procedures or SQL statements using an XML descriptor or annotations.

Contents

MyBatis is free software that is distributed under the Apache License 2.0.

MyBatis is a fork of iBATIS 3.0 and is maintained by a team that includes the original creators of iBATIS.

Feature summary

Unlike ORM frameworks, MyBatis does not map Java objects to database tables but Java methods to SQL statements.

MyBatis lets you use all your database functionality like stored procedures, views, queries of any complexity and vendor proprietary features. It is often a good choice for legacy or de-normalized databases or to obtain full control of SQL execution.

It simplifies coding compared to JDBC. SQL statements are executed with a single line.

MyBatis provides a mapping engine that maps SQL results to object trees in a declarative way.

SQL statements can be built dynamically by using a built-in language with XML-like syntax or with Apache Velocity using the Velocity integration plugin.

MyBatis integrates with Spring Framework and Google Guice. This feature allows one to build business code free of dependencies.

MyBatis supports declarative data caching. A statement can be marked as cacheable so any data retrieved from the database will be stored in a cache and future executions of that statement will retrieve the cached data instead hitting the database. MyBatis provides a default cache implementation based on a Java HashMap and default connectors for integrating with: OSCache, Ehcache, Hazelcast and Memcached. It provides an API to plug other cache implementations.

Usage

SQL statements are stored in XML files or annotations. Below depicts a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:

packageorg.mybatis.example;publicinterfaceBlogMapper{@Select("select * from Blog where id = #{id}")BlogselectBlog(intid);}

The sentence is executed as follows.

BlogMappermapper=session.getMapper(BlogMapper.class);Blogblog=mapper.selectBlog(101);

SQL statements and mappings can also be externalized to an XML file as follows.

<?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"><mappernamespace="org.mybatis.example.BlogMapper"><selectid="selectBlog"parameterType="int"resultType="Blog">         select * from Blog where id = #{id}</select></mapper>

Statements can also be executed using the MyBatis API.

Blogblog=session.selectOne("org.mybatis.example.BlogMapper.selectBlog",101);

For details, please refer to the User Guide available at MyBatis site. See external links.

Spring integration

MyBatis integrates with Spring Framework. This module allows MyBatis to participate in Spring transactions. It will also build MyBatis mappers and sessions and inject them into other beans.

The following sample shows a basic XML configuration that sets up a mapper and injects it into a "BlogService" bean.

<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><propertyname="dataSource"ref="dataSource"/></bean><beanid="blogMapper"class="org.mybatis.spring.mapper.MapperFactoryBean"><propertyname="sqlSessionFactory"ref="sqlSessionFactory"/><propertyname="mapperInterface"value="org.mybatis.example.BlogMapper"/></bean><beanid="blogService"class="org.mybatis.example.BlogServiceImpl"><propertyname="blogMapper"ref="blogMapper"/></bean>

Calling MyBatis is now just calling a bean:

publicclassBlogServiceImplimplementsBlogService{privateBlogMapperblogMapper;publicvoidsetBlogMapper(BlogMapperblogMapper){this.blogMapper=blogMapper;}publicvoiddoSomethingWithABlog(intblogId){Blogblog=blogMapper.selectBlog(blogId);...}}

Velocity language

The Velocity language driver lets you use Apache Velocity to generate your dynamic SQL queries on the fly.

<selectid="findPerson"lang="velocity">#set($pattern=$_parameter.name+'%')   SELECT *   FROM person   WHERE name LIKE @{pattern, jdbcType=VARCHAR} </select>

MyBatis Generator

MyBatis provides a code generator. MyBatis Generator will introspect a database table (or many tables) and generate MyBatis artifacts needed to perform CRUD operations (Create, Retrieve, Update, Delete).

An Eclipse plugin is available.

It will preserve any custom code in case of regeneration but only if you use the Eclipse plugin.

MyBatis Migrations

MyBatis Migrations is a Java command line tool that keeps track of database schema changes managing DDL files (known as migrations).

Migrations allows to query the current status of the database, apply schema changes and also undo them. It also helps to detect and solve concurrent database schema changes made by different developers.

History

MyBatis project is a subsidiary of iBATIS 3.0 and maintained by a team which includes the original creators of iBATIS.

The project was created on May 19, 2010 when Apache iBATIS 3.0 was published and the team announced that the development will continue under a new name and a new home at Google Code. [2]

[3]

See also

Related Research Articles

Object–relational mapping in computer science is a programming technique for converting data between type systems using object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language. There are both free and commercial packages available that perform object–relational mapping, although some programmers opt to construct their own ORM tools.

Hibernate ORM is an object–relational mapping tool for the Java programming language. It provides a framework for mapping an object-oriented domain model to a relational database. Hibernate handles object–relational impedance mismatch problems by replacing direct, persistent database accesses with high-level object handling functions.

A user-defined function (UDF) is a function provided by the user of a program or environment, in a context where the usual assumption is that functions are built into the program or environment. UDFs are usually written for the requirement of its creator.

iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. In Java, the objects are POJOs. The mappings are decoupled from the application logic by packaging the SQL statements in XML configuration files. The result is a significant reduction in the amount of code that a developer needs to access a relational database using lower level APIs like JDBC and ODBC.

The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Although the framework does not impose any specific programming model, it has become popular in the Java community as an addition to the Enterprise JavaBeans (EJB) model. The Spring Framework is open source.

Jakarta Persistence is a Jakarta EE application programming interface specification that describes the management of relational data in enterprise Java applications.

Scriptella is an open source ETL (Extract-Transform-Load) and script execution tool written in Java. It allows the use of SQL or another scripting language suitable for the data source to perform required transformations. Scriptella does not offer any graphical user interface.

The SQuirreL SQL Client is a database administration tool. It uses JDBC to allow users to explore and interact with databases via a JDBC driver. It provides an editor that offers code completion and syntax highlighting for standard SQL. It also provides a plugin architecture that allows plugin writers to modify much of the application's behavior to provide database-specific functionality or features that are database-independent. As this desktop application is written entirely in Java with Swing UI components, it should run on any platform that has a JVM.

Oracle Application Framework is a proprietary framework developed by Oracle Corporation for application development within the Oracle E-Business Suite (EBS). The framework is also available to customers for personalizations, customizations and custom-application development.

Apache Cayenne Open-source persistence framework

Apache Cayenne is an open source persistence framework licensed under the Apache License, providing object-relational mapping (ORM) and remoting services. Cayenne binds one or more database schemas directly to Java objects, managing atomic commit and rollbacks, SQL generation, joins, sequences, and more. With Cayenne's Remote Object Persistence, those Java objects can even be persisted out to clients via Web Services. Or, with native XML serialization, objects can be further persisted to non-Java clients—such as an Ajax-capable browser.

Judoscript is a general purpose programming language designed primarily for scripting tasks on the Java platform. It was conceived and developed by James Jianbo Huang, starting in late 2001. Judoscript was one of the first so-called Java scripting languages; but its most striking characteristics is its audacious multi-domain support philosophy and practice.

Apache Cassandra Free and open-source database management system

Cassandra is a free and open-source, distributed, wide-column store, NoSQL database management system designed to handle large amounts of data across many commodity servers, providing high availability with no single point of failure. Cassandra offers support for clusters spanning multiple datacenters, with asynchronous masterless replication allowing low latency operations for all clients. Cassandra was designed to implement a combination of Amazon's Dynamo distributed storage and replication techniques combined with Google's Bigtable data and storage engine model.

Apache Empire-db is a Java library that provides a high level object-oriented API for accessing relational database management systems (RDBMS) through JDBC. Apache Empire-db is open source and provided under the Apache License 2.0 from the Apache Software Foundation.

Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access a database. It is a Java-based data access technology used for Java database connectivity. It is part of the Java Standard Edition platform, from Oracle Corporation. It provides methods to query and update data in a database, and is oriented toward relational databases. A JDBC-to-ODBC bridge enables connections to any ODBC-accessible data source in the Java virtual machine (JVM) host environment.

jOOQ Object Oriented Querying, commonly known as jOOQ, is a light database-mapping software library in Java that implements the active record pattern. Its purpose is to be both relational and object oriented by providing a domain-specific language to construct queries from classes generated from a database schema.

Apache Hive Database engine

Apache Hive is a data warehouse software project built on top of Apache Hadoop for providing data query and analysis. Hive gives an SQL-like interface to query data stored in various databases and file systems that integrate with Hadoop. Traditional SQL queries must be implemented in the MapReduce Java API to execute SQL applications and queries over distributed data. Hive provides the necessary SQL abstraction to integrate SQL-like queries (HiveQL) into the underlying Java without the need to implement queries in the low-level Java API. Since most data warehousing applications work with SQL-based querying languages, Hive aids portability of SQL-based applications to Hadoop. While initially developed by Facebook, Apache Hive is used and developed by other companies such as Netflix and the Financial Industry Regulatory Authority (FINRA). Amazon maintains a software fork of Apache Hive included in Amazon Elastic MapReduce on Amazon Web Services.

In database management systems (DBMS), a prepared statement or parameterized statement is a feature used to pre-compile SQL code, separating it from data. Benefits of prepared statements are:

Apache Drill Open-source software framework

Apache Drill is an open-source software framework that supports data-intensive distributed applications for interactive analysis of large-scale datasets. Built chiefly by contributions from developers from MapR, Drill is inspired by Google's Dremel system, also productized as BigQuery. Drill is an Apache top-level project.

Persist is a Java-based ORM/DAO tool. It provides only the minimal amount of functionalities necessary to map objects or maps from database queries and to statement parameters.

References

  1. "Releases · mybatis/mybatis-3". github.com. Retrieved 2022-05-28.
  2. iBATIS Project Team Moving to Google Code
  3. Bye Google Code welcome Github