前言:MyBatis是一個支持普通SQL查詢,存儲過程以及高級映射的持久層框架,也被稱爲ORM(Object/Relational Mapping,即對象關係映射)框架。以面向對象的方式來操作持久化對象
- 下載:https://github.com/mybatis/mybatis-3/releases
- 我使用的數據庫MariaDB,與mysql基本一樣
- MariaDB的jar包下載:https://downloads.mariadb.com/Connectors/java/connector-java-1.8.0/
1. MyBatis的工作原理
- 讀取MyBatis配置文件(如:mybatis-config.xml),作爲MyBatis的全局配置文件,配置了MyBatis的運行環境等,主要是獲取數據庫連接。
- 加載映射文件(如:StudentMapper),StudentMapper文件即SQL映射文件,改文件中配置了操作數據庫的SQL語句,需要在mybatis-config.xml中加載才能執行。
- 構造會話工廠(SqlSessionFactory)
- 構造會話對象(SqlSession),包含了執行SQL的所有方法
- Executor執行器,MyBatis底層定義了Executor接口來操作數據庫
- MapperedStatement對象,StudentMapper文件中一個SQL對應一個MapperedStatement,SQL的id即是MapperedStatement的id
- 輸入參數映射
- 輸出結果映射
2. MyBatis的入門程序
- 在mariaDB中創建mybatis的數據庫,創建表t_student,並插入幾行數據
- Eclipse中創建一個web項目,導入已經下好的mybastis的jar包,包括連接數據庫的jar包
- 在src目錄下,創建一個com.xhh.po包,創建持久化類Student,與數據庫字段對應
student.java
package com.xhh.po;
public class Student {
private Integer id;
private String name;
private String age;
private String sex;
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 getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
- 在src目錄下,創建com.xhh.mapper包,並在包中創建映射文件StudentMapper.xml
文件中的約束配置在MyBatis使用手冊中可以找到
StudentMapper.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.xhh.mapper.StudentMapper">
<select id="selectStudentById" parameterType="Integer" resultType="com.xhh.po.Student">
select * from t_student where id = #{id}
</select>
</mapper>
namespace
該屬性爲這個<mapper>
指定了唯一的命名空間,通常會設置成包名+SQL映射文件名<select>
中的信息用於執行查詢操作的配置,id屬性是<select>
元素在映射文件中的唯一標識,parameterType屬性用於指定傳入的參數的類型,resultType屬性用於指定返回結果的類型#{id}
表示該佔位符待接收參數的名稱爲id
- 在src目錄下,創建MyBatis的核心配置文件mybatis-config.xml
同樣在使用手冊中也可以找到約束配置,它將配置分爲兩個步驟,第一步配置了環境,第二步配置了Mapper的位置
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>
<properties resource="db.properties"></properties>
<environments default="mariadb">
<environment id="mariadb">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/xhh/mapper/StudentMapper.xml" />
</mappers>
</configuration>
<properties resource="db.properties"></properties>
如上所示,可以創建在src目錄下db.properties,將連接數據庫的信息寫在db.properties中,然後通過${}
使用,它可以讓我們更靈活的修改信息。
db.properties
jdbc.driver=org.mariadb.jdbc.Driver
jdbc.url=jdbc:mariadb://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456
- 在src目錄下,創建com.xhh.test包,創建測試類DBTest,並編寫測試方法
package com.xhh.test;
import java.io.IOException;
import java.io.InputStream;
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 org.junit.Test;
import com.xhh.po.Student;
public class DBTest {
// id查找一個學生
@Test
public void findStudentById() throws IOException {
// 1.讀取配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 2.根據配置文件構建SqlSessionFactory
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
// 3.構建會話
SqlSession sqlSession = build.openSession();
Student student = sqlSession.selectOne("com.xhh.mapper.StudentMapper.selectStudentById",1);
System.out.println(student.toString());
sqlSession.close();
}
}
結果:
- 因爲MyBatis默認使用log4j輸出日誌信息,所以如果要查看控制檯輸出的SQL語句,那麼就需要配置日誌文件,在src中創建log4j.properties文件
文件的內容可以在剛纔下載的mybatis中的pdf查看
創建的配置文件如下:
log4j.properties
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.xhh=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
其中log4j.logger.com.xhh=DEBUG用於將com.xhh包下所有類的日誌級別設置爲DEBUG
結果:
3. MyBatis進行增刪改查
在入門程序的基礎上
- 添加學生信息
在MyBatis的映射文件中,添加操作是通過<insert>
元素來實現的,向t_student中插入一條數據,在StudentMapper.xml添加如下配置
<insert id="addStudent" parameterType="com.xhh.po.Student">
insert into t_student(name,age,sex)
values(#{name},#{age},#{sex})
</insert>
在測試類DBTest中,添加測試方法
@Test
public void addStudent() throws Exception {
// 1.讀取配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 2.根據配置文件構建SqlSessionFactory
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
// 3.構建會話
SqlSession sqlSession = build.openSession();
Student student = new Student();
student.setName("趙五");
student.setSex("男");
student.setAge("20");
int row = sqlSession.insert("com.xhh.mapper.StudentMapper.addStudent", student);
if (row > 0) {
System.out.println("添加" + row + "個學生成功");
} else {
System.out.println("添加失敗");
}
sqlSession.commit();
sqlSession.close();
}
可以使用@Ignore
添加在之前的測試方法上,這樣就不會執行之前的測試方法。
發現這兩個方法前3個步驟基本相同,所以可以寫一個工具類,減少代碼量
- 在src中創建包com.xhh.util,創建MyBatisUtils類
MyBatisUtils.java
package com.xhh.util;
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 MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
把前3個步驟改成: SqlSession sqlSession = MyBatisUtils.getSession();
- 刪除學生信息
在MyBatis的映射文件中,刪除操作是通過<delete>
元素來實現的,在StudentMapper.xml添加如下配置
<delete id="deleteStudent" parameterType="Integer">
delete from t_student where id = #{id}
</delete>
在測試類DBTest中,添加測試方法
@Test
public void deleteStudentById() {
SqlSession sqlSession = MyBatisUtils.getSession();
int row = sqlSession.delete("com.xhh.mapper.StudentMapper.deleteStudent", 3);
if (row > 0) {
System.out.println("刪除一個學生成功");
} else {
System.out.println("刪除失敗");
}
sqlSession.commit();
sqlSession.close();
}
- 查詢所有學生信息
跟查詢一個學生信息基本相同,在StudentMapper.xml添加如下配置
<select id="selectStudentAll" resultType="com.xhh.po.Student">
select * from t_student
</select>
編寫測試方法
@Test
public void findStudentAll() {
SqlSession sqlSession = MyBatisUtils.getSession();
List<Student> students = sqlSession.selectList("com.xhh.mapper.StudentMapper.selectStudentAll");
for (Student student : students) {
System.out.println(student.toString());
}
sqlSession.close();
}
- 更新學生信息
在MyBatis的映射文件中,更新操作是通過<update>
元素來實現的,在StudentMapper.xml添加如下配置
<update id="updateStudent" parameterType="com.xhh.po.Student">
update t_student set
name = #{name},age = #{age},sex = #{sex}
where id = #{id}
</update>
編寫測試方法
@Test
// 更新學生信息
public void updateStudent() {
SqlSession sqlSession = MyBatisUtils.getSession();
Student student = new Student();
student.setId(3);
student.setName("趙五");
student.setSex("女");
student.setAge("17");
int row = sqlSession.update("com.xhh.mapper.StudentMapper.updateStudent", student);
if (row > 0) {
System.out.println("更新學生信息成功");
} else {
System.out.println("更新學生信息失敗");
}
sqlSession.close();
}
完成。