MyBatis 是什麼?java
本篇介紹如何在 IDEA 中使用 MyBatis 開發 Java 項目,而且使用 Maven 來管理和集成依賴庫。mysql
Maven 的優勢在於能夠方便的管理各類依賴包,咱們能夠使用 Maven 來管理 MyBatis 和 MySQL 的相關庫的依賴。
新建的 Maven 項目目錄關係入下:
最後,Maven 目錄以下:
新建一個 Maven 工程後,在 pom.xml 中配置 MyBatis 和 mysql 依賴庫。sql
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.libaoquan.learnssm.c3</groupId> <artifactId>learnmybatis</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <mybatis.version>3.4.5</mybatis.version> <mysql.version>8.0.11</mysql.version> </properties> <dependencies><!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies> </project>
在 resources 文件夾下新建 mybatis-config.xml 文件,填入 MyBatis 配置信息。
其中:數據庫
<?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="worker" type="net.libaoquan.learnssm.c3.learnmybatis.pojo.Worker"/> </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/ssm"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!-- 映射文件 --> <mappers> <mapper resource="mapper/workerMapper.xml"/> </mappers> </configuration>
建立數據庫並填入數據。apache
create database ssm; create table worker ( id int primary key auto_increment, name varchar(255), note varchar(255) ); alter table worker default character set utf8; alter table worker change name name varchar(255) character set utf8; alter table worker change note note varchar(255) character set utf8; insert into worker (name, note) values ('章三', '工程師'); insert into worker (name, note) values ('王如', '工程師'); insert into worker (name, note) values ('李斯', '工程師'); insert into worker (name, note) values ('趙翼', '設計師'); insert into worker (name, note) values ('孫起', '設計師');
一個 POJO 類,簡單來講就是與數據庫中一張表相關聯的一個 Java 類。
在這裏,新建一個 POJO 類 Worker,與數據表 worker 相關聯,能夠使自動填充填寫 setter 和 getter 方法。session
package net.libaoquan.learnssm.c3.learnmybatis.pojo; public class Worker { private Integer id; private String name; private String note; public Worker() { this.id = 0; this.name = ""; this.note = ""; } public Worker(Integer id, String name, String note) { this.id = id; this.name = name; this.note = note; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } @Override public String toString() { return "Worker{" + "id=" + id + ", name='" + name + '\'' + ", note='" + note + '\'' + '}'; } }
一個 xml 映射器用來實現如何處理與之關聯的 POJO 類的數據邏輯,通常在接口中實現處理邏輯,具體的實現由 xml 文件中的 sql 語句實現。
使用 workerMapper.xml 以及 WorkerMapper 接口實現 xml 映射器。
首先,新建一個接口 workerMapper,其中方法 getWorker 是一個 Worker 類的處理邏輯。mybatis
package net.libaoquan.learnssm.c3.learnmybatis.mapper; import net.libaoquan.learnssm.c3.learnmybatis.pojo.Worker; public interface WorkerMapper { public Worker getWorker(int id); }
接着,在 resources 目錄下創建 mapper 目錄,建立 workerMapper.xml。
其中:app
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//rnybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="net.libaoquan.learnssm.c3.learnmybatis.mapper.WorkerMapper"> <select id="getWorker" parameterType="int" resultType="worker"> select id, name, note from worker where id= #{id} </select> </mapper>
新建 test 類,測試配置是否正確。
使用 2 種 SQL 發送器,分別是用 SqlSession 直接發送,和經過 SqlSession獲取 Mapper接口再發送。
通常推薦使用第二種。框架
package net.libaoquan.learnssm.c3.learnmybatis; import net.libaoquan.learnssm.c3.learnmybatis.mapper.WorkerMapper; import net.libaoquan.learnssm.c3.learnmybatis.pojo.Worker; 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 java.io.IOException; import java.io.InputStream; public class test { public static void main(String[] args){ SqlSessionFactory SqlSessionFactory = null; String resource = "mybatis-config.xml"; InputStream inputStream; SqlSession sqlSession = null; try { inputStream = Resources.getResourceAsStream (resource); SqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); sqlSession = SqlSessionFactory.openSession(); // 用 SqlSession 直接發送 Worker t = (Worker)sqlSession.selectOne("net.libaoquan.learnssm.c3.learnmybatis.mapper.WorkerMapper.getWorker", 1); System.out.println(t.toString()); // 經過 SqlSession獲取 Mapper接口再發送 WorkerMapper tm = sqlSession.getMapper(WorkerMapper.class); Worker t2 = tm.getWorker(2); System.out.println(t2.toString()); sqlSession.commit(); } catch (IOException e) { e.printStackTrace(); sqlSession.rollback(); } finally { if (sqlSession != null){ sqlSession.close(); } } } }