这是 MyBatis Java 教程。本教程涵盖了使用 Java 和 MyBatis 进行 MySQL 编程的基础知识。
MyBatis
MyBatis是一个 Java 持久性框架,它使用 XML 描述符或注释将对象与存储过程或 SQL 语句耦合在一起。与 ORM 框架不同,MyBatis 不会将 Java 对象映射到数据库表,而是将 Java 方法映射到 SQL 语句。MyBatis 允许使用所有数据库功能,如存储过程、视图、任何复杂性的查询和供应商专有功能。
使用 MyBatis 的好处是:
- 开箱即用的表/查询缓存
- 减少大部分 JDBC 样板文件
- 提高生产力
- SQL 代码与 Java 类的分离
关于 MySQL 数据库
MySQL是领先的开源数据库管理系统。它是一个多用户、多线程的数据库管理系统。MySQL 在网络上特别流行。MySQL有两个版本:MySQL服务器系统和MySQL嵌入式系统。
Maven 依赖项
在pom.xml文件中,我们添加以下依赖项:
mysql mysql-connector-java5.1.40 org.mybatis mybatis3.4.2
POM 文件有两个依赖项:MyBatis 库和 MySQL 驱动程序。
MyBooks 表
本教程中的一些示例使用该MyBooks表。
mybooks.sqlCREATE TABLE MyBooks(Id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
Author VARCHAr(30), Title VARCHAr(60), Published INTEGER, Remark VARCHAr(150));
INSERT INTO MyBooks(Author, Title, Published, Remark) VALUES ('Leo Tolstoy', 'War and Peace', 1869, 'Napoleonic wars');
INSERT INTO MyBooks(Author, Title, Published, Remark) VALUES ('Leo Tolstoy', 'Anna Karenina', 1878, 'Greatest book of love');
INSERT INTO MyBooks(Author, Title, Published, Remark) VALUES ('Jeff Prosise', 'Programming Windows with MFC', 1999, 'Classic book about MFC');
INSERT INTO MyBooks(Author, Title, Published, Remark) VALUES ('Tom Marrs', 'JBoss at Work', 2005, 'JBoss practical guide');
INSERT INTO MyBooks(Author, Title, Published, Remark) VALUES ('Debu Panda', 'EJB3 in Action', 2007, 'Introduction to Enterprice Java Beans');
MyBooks这些 SQL 命令在 MySQLtestdb数据库 中 创建一个表。
MySQL版本
在第一个示例中,我们获取 MySQL 的版本。在此示例中,我们使用注释将对象映射到 SQL 语句。
图:MyBatisMySQLVersion 项目结构
这是 NetBeans 中的项目结构。
mybatis-config.xml每个 MyBatis 项目都有一个主要的 XML 配置文件。在这里,我们为 MySQL 定义了一个数据源。
MyMapper.javapackage com.zetcode.version;
import org.apache.ibatis.annotations.Select;
public interface MyMapper {
@Select("SELECT VERSION()")
public String getMySQLVersion();
}
通过@Select注解,我们将getMySQLVersion() 方法映射到注解中指定的 SQL 语句。获取 MySQL 版本的 SQL 语句是SELECT VERSION().
MyBatisMySQLVersion.javapackage 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 {
private 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);
reader.close();
try {
session = factory.openSession();
String version = session.selectOne("getMySQLVersion");
System.out.println(version);
} finally {
if (session != null) {
session.close();
}
}
}
}
我们连接到数据库并获取 MySQL 的版本。
String resource = "mybatis-config.xml"; Reader reader = null; SqlSession session = null; reader = Resources.getResourceAsReader(resource);
读取配置文件。
factory = new SqlSessionFactoryBuilder().build(reader);
SqlSessionFactoryBuilder用于构建SqlSession 实例 。
factory.getConfiguration().addMapper(MyMapper.class);
通过该addMapper()方法,我们将映射类添加到工厂。
session = factory.openSession();
该openSession()方法创建一个SqlSession. SqlSession是使用 MyBatis 的主要 Java 接口。通过这个接口,我们执行命令、获取映射器和管理事务。
String version = session.selectOne("getMySQLVersion");
该selectOne()方法检索从语句键映射的单行。语句键是映射器类中方法的名称。
System.out.println(version);
版本打印到控制台。
} finally {
if (session != null) {
session.close();
}
}
最后,会话关闭。
MySQL 版本 2
在第二个示例中,我们也将检索 MySQL 的版本;这次我们使用 XML 映射器而不是注释。
mybatis-config.xml使用
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 {
private 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);
reader.close();
try {
session = factory.openSession();
String version = session.selectOne("mysqlVersion");
System.out.println(version);
} finally {
if (session != null) {
session.close();
}
}
}
}
这是主要课程。不同的是,我们没有添加带有 的映射器addMapper(),而是从配置文件中读取的。
MyBatis Java 配置
可以在不使用 XML 的情况下在纯 Java 中配置 MyBatis。在下面的示例中,我们将找出表中的书籍数量。
MyMapper.javapackage com.zetcode.map;
import org.apache.ibatis.annotations.Select;
public interface MyMapper {
@Select("SELECT COUNT(*) FROM MyBooks")
public int getNumberOfBooks();
}
MyMapper包含计算表中行数的 SQL 代码MyBooks。
MyDataSourceFactory.javapackage com.zetcode.jconfig;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
public class MyDataSourceFactory implements DataSourceFactory {
private Properties prop;
@Override
public DataSource getDataSource() {
PooledDataSource ds = new PooledDataSource();
ds.setDriver(prop.getProperty("driver"));
ds.setUrl(prop.getProperty("url"));
ds.setUsername(prop.getProperty("user"));
ds.setPassword(prop.getProperty("password"));
return ds;
}
@Override
public void setProperties(Properties prprts) {
prop = prprts;
}
}
MyDataSourceFactoryPooledDataSource 从给定的属性创建一个。PooledDataSource是一个简单的、同步的、线程安全的数据库连接池。
MyBatisJavaConfClient.javapackage com.zetcode.client;
import com.zetcode.jconfig.MyDataSourceFactory;
import com.zetcode.jconfig.MyMapper;
import java.io.IOException;
import java.util.Properties;
import javax.sql.DataSource;
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;
public class MyBatisJavaConfClient {
private static SqlSessionFactory sesFact = null;
public static void main(String[] args) throws IOException {
Properties prop = new Properties();
prop.setProperty("driver", "com.mysql.jdbc.Driver");
prop.setProperty("url", "jdbc:mysql://localhost:3306/testdb");
prop.setProperty("user", "testuser");
prop.setProperty("password", "test623");
MyDataSourceFactory mdsf = new MyDataSourceFactory();
mdsf.setProperties(prop);
DataSource ds = mdsf.getDataSource();
TransactionFactory trFact = new JdbcTransactionFactory();
Environment environment = new Environment("development", trFact, ds);
Configuration config = new Configuration(environment);
config.addMapper(MyMapper.class);
sesFact = new SqlSessionFactoryBuilder().build(config);
try (SqlSession session = sesFact.openSession()) {
int numOfBooks = session.selectOne("getNumberOfBooks");
System.out.format("There are %d books", numOfBooks);
}
}
}
在 中MyBatisJavaConfClient,我们使用 Java 代码配置 MyBatis,构建 SQL 会话,并执行getNumberOfBooks()方法。
Properties prop = new Properties();
prop.setProperty("driver", "com.mysql.jdbc.Driver");
prop.setProperty("url", "jdbc:mysql://localhost:3306/testdb");
prop.setProperty("user", "testuser");
prop.setProperty("password", "test623");
这里我们设置数据库属性。
MyDataSourceFactory mdsf = new MyDataSourceFactory(); mdsf.setProperties(prop); DataSource ds = mdsf.getDataSource();
我们通过 获取数据源MyDataSourceFactory。
TransactionFactory trFact = new JdbcTransactionFactory();
Environment environment = new Environment("development", trFact, ds);
Configuration config = new Configuration(environment);
config.addMapper(MyMapper.class);
此代码替换 XML 配置。我们使用JdbcTransactionFactory、 Environment和Configuration类。
sesFact = new SqlSessionFactoryBuilder().build(config);
类的实例Configuration被传递给SqlSessionFactoryBuilder's build()方法。
动态 SQL
动态 SQL 允许我们使用诸如 、 或 等标签创建动态
首先我们提供mybatis-config.xml配置文件。
mymapper.xmlmymapper.xml包含动态 SQL 表达式 。
Id = #{id}
package com.zetcode.mybatisdynamicsql.bean;
public class Book {
private Long id;
private String author;
private String title;
private int published;
private String remark;
public Book() {};
public Book(String author, String title, int published,
String remark) {
this.author = author;
this.title = title;
this.published = 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 getPublished() {
return published;
}
public void setPublished(int published) {
this.published = published;
}
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 + ", published=" + published
+ ", remark=" + remark + '}';
}
}
这Book是映射到我们的结果数据的 bean。
MyBatisDynamicSQL .javapackage com.zetcode.mybatisdynamicsql;
import com.zetcode.mybatisdynamicsql.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 MyBatisDynamicSQL {
private 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();
Book book = session.selectOne("getBook", 1);
System.out.println(book);
List books = session.selectList("getBook");
for (Book b : books) {
System.out.println(b);
}
} finally {
if (session != null) {
session.close();
}
}
}
}
使用一个语句键,我们检索一本特定的书和所有的书。
Book book = session.selectOne("getBook", 1);
在这里,我们检索由其 ID 标识的一本书。
Listbooks = session.selectList("getBook");
在这里,我们检索所有书籍;第二个参数没有传递。
图书
在下一个示例中,我们将从数据库表中插入和读取书籍。
图:MyBatisMySQLBooks 项目结构
这是 NetBeans 中的项目结构。
Book.javapackage com.zetcode.books.bean;
public class Book {
private Long id;
private String author;
private String title;
private int published;
private String remark;
public Book() {};
public Book(String author, String title, int published,
String remark) {
this.author = author;
this.title = title;
this.published = 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 getPublished() {
return published;
}
public void setPublished(int published) {
this.published = published;
}
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 + ", published=" + published
+ ", remark=" + remark + '}';
}
}
这是Book豆子。MyBatis 会将表列映射到这个类。注意空构造函数的显式用法。
mybatis-config.xml在文件中,我们使用标签 mybatis-config.xml定义新Book 类型。
package com.zetcode.map;
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 MyBooks WHERe Id = #{id}")
public Book getBookById(Long id);
@Select("SELECT * FROM MyBooks WHERe Author = #{author}")
public List getBooksByAuthor(String author);
@Insert("INSERT INTO MyBooks(Author, Title, Published, Remark) "
+ "VALUES(#{author}, #{title}, #{published}, #{remark})")
public void insertBook(String author, String title, int published,
String remark);
}
在MyMapper界面中,我们有三个注解。
@Select("SELECT * FROM MyBooks WHERe Id = #{id}")
public Book getBookById(Long id);
此注解将getBookById()方法映射到指定的 SELECt 语句;该方法返回一个Book对象。
@Select("SELECT * FROM MyBooks WHERe Author = #{author}")
public List getBooksByAuthor(String author);
我们将 SELECT 语句映射到getBooksByAuthor()方法列表,该方法返回书籍对象列表。
@Insert("INSERT INTO MyBooks(Author, Title, Published, Remark) "
+ "VALUES(#{author}, #{title}, #{published}, #{remark})")
public void insertBook(String author, String title, int published,
String remark);
使用@Insert注释,我们将 INSERT 语句映射到insertBook()方法名称。
MyBatisBooks.javapackage com.zetcode.client;
import com.zetcode.map.MyMapper;
import com.zetcode.books.bean.Book;
import com.zetcode.util.MyBatisUtils;
import java.io.IOException;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
public class MyBatisBooks {
private static SqlSessionFactory factory = null;
public static void main(String[] args) throws IOException {
SqlSession session = null;
factory = MyBatisUtils.getSqlSessionFactory();
factory.getConfiguration().addMapper(MyMapper.class);
try {
session = factory.openSession();
Book book = session.selectOne("getBookById", 4L);
System.out.println(book);
List 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();
}
}
}
}
在主类中,我们通过 ID 选择一本书,选择一个作者的所有书籍,然后在表中插入一本新书。
Book book = session.selectOne("getBookById", 4L);
selectOne()使用 session 的方法 检索一本新书。
Listbooks = session.selectList("getBooksByAuthor", "Leo Tolstoy"); for (Book b : books) { System.out.println(b); }
Leo Tolstoy 的所有书籍都是使用 session 的selectList() 方法检索的。
session.update("insertBook", newBook);
session.commit();
update()使用会话的方法 插入新书。该方法将Book实例作为第二个参数。更改被提交到数据库中commit()。
这是 MyBatis 教程。



