- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Introduction to MyBatis
This is MyBatis Java tutorial. This tutorial covers the basics of MySQL programming with Java and MyBatis.
You might also want to check Java tutorial , MySQL Java tutorial , MySQL tutorial , or Spring JdbcTemplate tutorial on ZetCode.
MyBatis
MyBatis is a Java persistence framework that couples objects with stored procedures or SQL statements using an XML descriptor or annotations. Unlike ORM frameworks, MyBatis does not map Java objects to database tables but Java methods to SQL statements. MyBatis allows to use all database functionality like stored procedures, views, queries of any complexity and vendor proprietary features.
The benefits of using MyBatis are:
- out-of-the-box table/query caching
- reduction of much of the JDBC boilerplate
- increased productivity
- separation of SQL code from Java classes
About MySQL database
MySQL is a leading open source database management system. It is a multi user, multithreaded database management system. MySQL is especially popular on the web. MySQL comes in two versions: MySQL server system and MySQL embedded system.
Maven dependencies
In the pom.xml
file, we add the following dependencies:
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.39</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.0</version> </dependency> </dependencies>
The POM file has two dependencies: the MyBatis libraries and MySQL driver.
MySQL version
In the first example, we get the version of MySQL. In this example we map objects to SQL statements using annotations.

This is the project structure in NetBeans.
mybatis-config.xml
<?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> <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/testdb"/> <property name="username" value="testuser"/> <property name="password" value="test623"/> </dataSource> </environment> </environments> </configuration>
Each MyBatis project has a primary XML configuration file. Here we have defined a datasource for MySQL.
MyMapper.java
package com.zetcode.version; import org.apache.ibatis.annotations.Select; public interface MyMapper { @Select("SELECT VERSION()") public String getMySQLVersion(); }
With the @Select
annotation, we map the getMySQLVersion()
method to the SQL statement specified in the annotation. The SQL statement to get the version of MySQL is SELECT VERSION()
.
MyBatisMySQLVersion.java
package com.zetcode.version; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisMySQLVersion { public static SqlSessionFactory factory = null; public static void main(String[] args) throws IOException { String resource = "mybatis-config.xml"; Reader reader = null; SqlSession session = null; reader = Resources.getResourceAsReader(resource); factory = new SqlSessionFactoryBuilder().build(reader); factory.getConfiguration().addMapper(MyMapper.class); try { session = factory.openSession(); String version = session.selectOne("getMySQLVersion"); System.out.println(version); } finally { if (session != null) { session.close(); } } } }
We connect to the database and get the version of MySQL.
String resource = "mybatis-config.xml"; Reader reader = null; SqlSession session = null; reader = Resources.getResourceAsReader(resource);
The configuration file is read.
factory = new SqlSessionFactoryBuilder().build(reader);
The SqlSessionFactoryBuilder
is used to build SqlSession
instances.
factory.getConfiguration().addMapper(MyMapper.class);
With the addMapper()
method, we add the mapping class to the factory.
session = factory.openSession();
The openSession()
method creates an SqlSession
. SqlSession
is the primary Java interface for working with MyBatis. Through this interface we execute commands, get mappers and manage transactions.
String version = session.selectOne("getMySQLVersion");
The selectOne()
method retrieves a single row mapped from the statement key. The statement key is the name of the method in the mapper class.
System.out.println(version);
The version is printed to the console.
} finally { if (session != null) { session.close(); } }
In the end, the session is closed.
MySQL version 2
In the second example, we are going to retrieve the version of MySQL too; this time we use an XML mapper instead of annotations.
mybatis-config.xml
<?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> <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/testdb"/> <property name="username" value="testuser"/> <property name="password" value="test623"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mymapper.xml"/> </mappers> </configuration>
With the <mappers>
tag, we specify the mapping file.
mymapper.xml
<?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="com.zetcode"> <select id="mysqlVersion" resultType="String"> SELECT VERSION() </select> </mapper>
We define the mapping with the <select>
tag.
MyBatisMySQLVersion2.java
package com.zetcode.version2; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisMySQLVersion2 { public static SqlSessionFactory factory = null; public static void main(String[] args) throws IOException { String resource = "mybatis-config.xml"; Reader reader = null; SqlSession session = null; reader = Resources.getResourceAsReader(resource); factory = new SqlSessionFactoryBuilder().build(reader); try { session = factory.openSession(); String version = session.selectOne("mysqlVersion"); System.out.println(version); } finally { if (session != null) { session.close(); } } } }
This is the main class. The difference is that we do not add a mapper with the addMapper()
, but it is read from the configuration file.
Books
In the next example, we will insert and read books from a database table.
The example uses a Books
table.
books.sql
CREATE TABLE Books(Id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, Author VARCHAR(30), Title VARCHAR(60), Published INTEGER, Remark VARCHAR(150)); INSERT INTO Books(Author, Title, Published, Remark) VALUES ('Leo Tolstoy', 'War and Peace', 1869, 'Napoleonic wars'); INSERT INTO Books(Author, Title, Published, Remark) VALUES ('Leo Tolstoy', 'Anna Karenina', 1878, 'Greatest book of love'); INSERT INTO Books(Author, Title, Published, Remark) VALUES ('Jeff Prosise', 'Programming Windows with MFC', 1999, 'Classic book about MFC'); INSERT INTO Books(Author, Title, Published, Remark) VALUES ('Tom Marrs', 'JBoss at Work', 2005, 'JBoss practical guide'); INSERT INTO Books(Author, Title, Published, Remark) VALUES ('Debu Panda', 'EJB3 in Action', 2007, 'Introduction to Enterprice Java Beans');
These SQL commands create a Books
table in MySQL testdb
database.

This is the project structure in NetBeans.
Book.java
package com.zetcode.books.bean; public class Book { private Long id; private String author; private String title; private int yearPublished; private String remark; public Book() {}; public Book(String author, String title, int published, String remark) { this.author = author; this.title = title; this.yearPublished = published; this.remark = remark; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getYearPublished() { return yearPublished; } public void setYearPublished(int yearPublished) { this.yearPublished = yearPublished; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Override public String toString() { return "Book{" + "id=" + id + ", author=" + author + ", " + "title=" + title + ", yearPublished=" + yearPublished + ", remark=" + remark + '}'; } }
This is the Book
bean. MyBatis will map table columns to this class. Notice the explicit usage of empty constructor.
mybatis-config.xml
<?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="Book" type="com.zetcode.books.bean.Book"/> </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/testdb"/> <property name="username" value="testuser"/> <property name="password" value="test623"/> </dataSource> </environment> </environments> </configuration>
In the mybatis-config.xml
file, we define the new Book
type with the <typeAlias>
tag.
MyMapper.java
package com.zetcode.books; import com.zetcode.books.bean.Book; import java.util.List; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; public interface MyMapper { @Select("SELECT * FROM Books WHERE Id = #{id}") public Book getBookById(Long id); @Select("SELECT * FROM Books WHERE Author = #{author}") public List<Book> getBooksByAuthor(String author); @Insert("INSERT INTO Books(Author, Title, Published, Remark) " + "VALUES(#{author}, #{title}, #{yearPublished}, #{remark})") public void insertBook(String author, String title, int yearPublished, String remark); }
In the MyMapper
interface, we have three annotations.
@Select("SELECT * FROM Books WHERE Id = #{id}") public Book getBookById(Long id);
This annotation maps the getBookById()
method to the specified SELECT statement; the method returns a Book
object.
@Select("SELECT * FROM Books WHERE Author = #{author}") public List<Book> getBooksByAuthor(String author);
We map a SELECT statement to a list of getBooksByAuthor()
method, which returns a list of book objects.
@Insert("INSERT INTO Books(Author, Title, Published, Remark) " + "VALUES(#{author}, #{title}, #{yearPublished}, #{remark})") public void insertBook(String author, String title, int yearPublished, String remark);
With the @Insert
annotation, we map an INSERT statement to the insertBook()
method name.
MyBatisMySQLBooks.java
package com.zetcode.books; import com.zetcode.books.bean.Book; import java.io.IOException; import java.io.Reader; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisMySQLBooks { public static SqlSessionFactory factory = null; public static void main(String[] args) throws IOException { String resource = "mybatis-config.xml"; Reader reader = null; SqlSession session = null; reader = Resources.getResourceAsReader(resource); factory = new SqlSessionFactoryBuilder().build(reader); factory.getConfiguration().addMapper(MyMapper.class); try { session = factory.openSession(); Book book = session.selectOne("getBookById", 4L); System.out.println(book); List<Book> books = session.selectList("getBooksByAuthor", "Leo Tolstoy"); for (Book b : books) { System.out.println(b); } Book newBook = new Book("Miguel de Cervantes", "Don Quixote", 1605, "First modern novel"); session.update("insertBook", newBook); session.commit(); } finally { if (session != null) { session.close(); } } } }
In the main class, we select a book by its ID, select all books from an author, and insert a new book into the table.
Book book = session.selectOne("getBookById", 4L);
A new book is retrieved using session's selectOne()
method.
List<Book> books = session.selectList("getBooksByAuthor", "Leo Tolstoy"); for (Book b : books) { System.out.println(b); }
All books from Leo Tolstoy are retrieved using session's selectList()
method.
session.update("insertBook", newBook); session.commit();
A new books is inserted with the session's update()
method. The method takes a Book
instance as the second parameter. The changes are committed to the database with commit()
.
This was the MyBatis tutorial. You might be also interested in JDBI tutorial , PostgreSQL Java tutorial , MongoDB Java tutorial , or MySQL tutorial .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论