部署jar包 -> 編寫MyBatis核心配置文件 -> 創(chuàng)建實體類 -> 創(chuàng)建DAO接口 -> 創(chuàng)建SQL映射文件 -> 編寫測試類"/>
在創(chuàng)建 MyBatis 項目之前,首先創(chuàng)建 website 數(shù)據(jù)表,SQL 語句如下。
DROP TABLE IF EXISTS `website`; CREATE TABLE `website` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `url` varchar(30) COLLATE utf8_unicode_ci DEFAULT '', `age` tinyint(3) unsigned NOT NULL, `country` char(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `createtime` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
創(chuàng)建 MyBatis 程序的步驟為:下載jar包 -> 部署jar包 -> 編寫MyBatis核心配置文件 -> 創(chuàng)建實體類 -> 創(chuàng)建DAO接口 -> 創(chuàng)建SQL映射文件 -> 編寫測試類
下面介紹如何使用 Eclipse IDE 創(chuàng)建一個簡單的 MyBatis 程序。
在 Eclipse 中創(chuàng)建 Web 項目 mybatisDemo,并將下載的 MyBatis 的核心 jar 包、依賴 jar 包以及 MySQL 數(shù)據(jù)庫的驅(qū)動 jar 包復(fù)制到 /WEB-INF/lib 目錄中。下載jar包詳細步驟在《MyBatis下載》一節(jié)講解。
MyBatis 默認使用 log4j 輸出日志信息,如果開發(fā)者需要查看控制臺輸出的 SQL 語句,可以在 classpath 路徑下配置其日志文件。在 mybatisDemo 的 src 目錄下創(chuàng)建 log4j.properties 文件,其內(nèi)容如下:
# Global logging configuration log4j.rootLogger=ERROR,stdout # MyBatis logging configuration... log4j.logger.net.biancheng=DEBUG # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
在日志文件中配置了全局的日志配置、MyBatis 的日志配置和控制臺輸出,其中 MyBatis 的日志配置用于將 net.biancheng 包下所有類的日志記錄級別設(shè)置為 DEBUG。該配置文件內(nèi)容不需要開發(fā)者全部手寫,可以從 MyBatis 使用手冊中的 Logging 小節(jié)復(fù)制,然后進行簡單修改。
在 src 目錄下創(chuàng)建一個名為 net.biancheng.po 的包,在該包中創(chuàng)建持久化類 Website。注意,在類中聲明的屬性與數(shù)據(jù)表 website 的字段一致。
Website 類代碼如下。
package net.biancheng.po; import java.util.Date; public class Website { private int id; private String name; private String url; private int age; private String country; private Date createtime; /*省略setter和getter方法*/ @Override public String toString() { return "id" + id + "name" + name + "url" + url + "age" + age + "country" + country + "createtime" + createtime; } }
在 src 目錄下創(chuàng)建 net.biancheng.mapper 包,在該包下創(chuàng)建映射文件 WebsiteMapper.xml。
WebsiteMapper.xml 文件內(nèi)容如下。
<?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="net.biancheng.mapper.WebsiteMapper"> <!-- 添加一個網(wǎng)站 --> <insert id="addWebsite" parameterType="net.biancheng.po.Website"> insert into website (name,url,age,country) values(#{name},#{url},#{age},#{country}) </insert> <!-- 查詢所有網(wǎng)站信息 --> <select id="selectAllWebsite" resultType="net.biancheng.po.Website"> select * from website </select> </mapper>
上述代碼中,<mapper> 元素是配置文件的根元素,它包含了 namespace 屬性,該屬性值通常設(shè)置為“包名+SQL映射文件名”,用于指定唯一的命名空間。
子元素 <select>、<insert> 中的信息用于執(zhí)行查詢、添加操作。在定義的 SQL 語句中,“#{}”表示一個占位符,相當于“?”,而“#{name}”表示該占位符待接收參數(shù)的名稱為 name。
MyBatis 核心配置文件主要用于配置數(shù)據(jù)庫連接和 MyBatis 運行時所需的各種特性,包含了設(shè)置和影響 MyBatis 行為的屬性。
在 src 目錄下創(chuàng)建 MyBatis 的核心配置文件 mybatis-config.xml,在該文件中配置了數(shù)據(jù)庫環(huán)境和映射文件的位置,具體內(nèi)容如下:
<?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> <settings> <setting name="logImpl" value="LOG4J" /> </settings> <!-- 配置mybatis運行環(huán)境 --> <environments default="development"> <environment id="development"> <!-- 使用JDBC的事務(wù)管理 --> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <!-- MySQL數(shù)據(jù)庫驅(qū)動 --> <property name="driver" value="com.mysql.jdbc.Driver" /> <!-- 連接數(shù)據(jù)庫的URL --> <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <!-- 將mapper文件加入到配置文件中 --> <mappers> <mapper resource="net/biancheng/mapper/WebsiteMapper.xml" /> </mappers> </configuration>
上述映射文件和配置文件都不需要讀者完全手動編寫,都可以從 MyBatis 使用手冊中復(fù)制,然后做簡單修改。
為了方便管理以后各框架集成所需的配置文件,可以在項目工程下新建 Source Folder 類型的 resources 目錄,并在此目錄下添加 MyBatis 的核心配置文件,默認文件名為 " configuration.xml"。但需要注意的是,為了方便在框架集成時更好地區(qū)分各個配置文件,我們一般將此文件名命名“mybatis-config.xml”,該文件用于配置數(shù)據(jù)庫連接信息和 MyBatis 的參數(shù)。
在 src 目錄下創(chuàng)建一個名為 net.biancheng.test 的包,在該包中創(chuàng)建 MyBatisTest 測試類。在測試類中首先使用輸入流讀取配置文件,然后根據(jù)配置信息構(gòu)建 SqlSessionFactory 對象。
接下來通過 SqlSessionFactory 對象創(chuàng)建 SqlSession 對象,并使用 SqlSession 對象的方法執(zhí)行數(shù)據(jù)庫操作。 MyBatisTest 測試類的代碼如下:
package net.biancheng.test; import java.io.IOException; import java.io.InputStream; 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; import net.biancheng.po.Website; public class Test { public static void main(String[] args) throws IOException { // 讀取配置文件mybatis-config.xml InputStream config = Resources.getResourceAsStream("mybatis-config.xml"); // 根據(jù)配置文件構(gòu)建SqlSessionFactory SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config); // 通過SqlSessionFactory創(chuàng)建SqlSession SqlSession ss = ssf.openSession(); // SqlSession執(zhí)行文件中定義的SQL,并返回映射結(jié)果 // 添加網(wǎng)站 Website website = new Website(); website.setName("編程幫"); website.setUrl("http://www.soo66.com/"); website.setAge(21); website.setCountry("CN"); ss.insert("net.biancheng.mapper.WebsiteMapper.addWebsite", website); // 查詢所有網(wǎng)站 List<Website> listWeb = ss.selectList("net.biancheng.mapper.WebsiteMapper.selectAllWebsite"); for (Website site : listWeb) { System.out.println(site); } // 提交事務(wù) ss.commit(); // 關(guān)閉 SqlSession ss.close(); } }
運行結(jié)果如下。
DEBUG [main] - ==> Preparing: insert into website (name,url,age,country) values(?,?,?,?) DEBUG [main] - ==> Parameters: 編程幫(String), http://www.soo66.com/(String), 21(Integer), CN(String) DEBUG [main] - <== Updates: 1 DEBUG [main] - ==> Preparing: select * from website DEBUG [main] - ==> Parameters: DEBUG [main] - <== Total: 1 Website[id=1,name=編程幫,url=http://www.soo66.com/,age=21,country=CN,createtime=Tue Feb 23 10:20:40 CST 2021]