文章目錄
一、以前的方式
1. 創建maven工程並導包
可以使用maven在線下載依賴,這裏因爲我已經下載好了jar包,直接導入就行了
新建一個lib文件夾,導入 mysql 驅動
和 mybatis-3.4.1
並將lib文件夾右鍵 add as library
可在官網下載 mybatis 的 jar 包 mybatis 官網
2. 創建數據庫表和對應的 JavaBean
數據庫表
CREATE TABLE `tbl_employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`last_name` varchar(255) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
對應的 JavaBean
public class Employee {
Integer id;
String lastName; //字段名最好和數據庫中的字段一致,如果不一致,可在sql語句中起別名
String gender;
String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String isGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", gender=" + gender +
", email='" + email + '\'' +
'}';
}
}
此處的 lastName 設置了和數據庫中的字段 last_Name 是不一致的,我們在後面的配置文件中需要給數據庫字段起對應的別名,否則會出錯。
3. 創建Mybatis全局配置文件
MyBatis 的全局配置文件包含了影響 MyBatis 行爲甚深 的設置(settings)和屬性(properties)信息、如數據 庫連接池信息等。指導着MyBatis進行工作。我們可以 參照官方文件的配置示例
新建 conf 文件夾,並右鍵 make Directory as source root
建立 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/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--將我們寫好的sql映射文件註冊到全局配置文件中-->
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
</configuration>
mappers 中註冊的 sql 映射文件如下
4. 創建sql映射文件
映射文件的作用就相當於是定義數據庫如何工作,編寫sql語句。這也是我們使用MyBatis時編寫的最多的文件。
同樣在conf文件夾下,創建 EmployeeMapper.xml
用來編寫 sql 語句
<?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.smallbeef.mybatis.EmployeeMapper">
<!--id:唯一標識
resultType: 返回值類型
#{id}:從傳遞過來的參數中取出id值-->
<select id="selectEmployee" resultType="com.smallbeef.mybatis.bean.Employee">
<!--由於lastName和數據庫字段不一致,需要在此起別名-->
select id, last_name lastName, email, gender from tbl_employee where id = #{id}
</select>
</mapper>
5. 測試
- 根據xml配置文件(全局配置文件),創建一個
SqlSessionFactory
對象 - sql 映射文件:配置了每一個sql, 以及 sql 的封裝規則
- 將 sql 映射文件註冊在全局配置文件中
- 寫代碼:
1)根據全局配置文件得到 SqlSessionFactory
2) 使用 sqlSession 工廠,獲取到sqlSession
對象使用它來執行增刪改查
一個 sqlSession 就是代表和數據庫的一次會話,用完關閉
3) 使用 sql 的唯一標識來告訴 MyBatis 執行哪個sql。sql都是保存在 sql 映射文件中的
public class MyBatisTest {
/**
* 1. 根據xml配置文件(全局配置文件),創建一個SqlSessionFactory對象
* 2. sql映射文件:配置了每一個sql,以及sql的封裝規則
* 3. 將sql映射文件註冊在全局配置文件中
* 4. 寫代碼:
* 1)根據全局配置文件得到SqlSessionFactory
* 2) 使用sqlSession工廠,獲取到sqlSession對象使用它來執行增刪改查
* 一個sqlSession就是代表和數據庫的一次會話,用完關閉
* 3) 使用sql的唯一標識來告訴MyBatis執行哪個sql.sql都是保存在sql映射文件中的
*
**/
@Test
public void MybatisTest() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2. 獲取sqlSession實例,能直接指向已經映射的sql語句
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
// 第一個參數:要執行的sql語句的唯一標識(推薦寫法:namespace + id 防止其他文件也有同樣的id導致衝突)
// 第二個參數;傳給sql語句進行執行的參數
Employee employee = sqlSession.selectOne("com.smallbeef.mybatis.EmployeeMapper.selectEmployee", 1);
System.out.println(employee);
} finally {
sqlSession.close();
}
}
}
查詢結果:
Employee{id=1, lastName=‘Tom’, gender=0, email=‘[email protected]’}
6. 項目結構
二、接口式編程(推薦)
1. 創建一個Dao層接口
在該接口中定義要執行的方法
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
}
2. 修改Mapper文件
- 修改名稱空間 namespace 爲接口的全類名
- 修改 id 爲接口的方法名
即將接口中的方法和 sql 映射文件進行綁定
<?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.smallbeef.mybatis.dao.EmployeeMapper">
<!--id:唯一標識
resultType: 返回值類型
#{id}:從傳遞過來的參數中取出id值-->
<!--public Employee getEmpById(Integer id)
將唯一標識id和接口中的方法進行綁定-->
<select id="getEmpById" resultType="com.smallbeef.mybatis.bean.Employee">
select id, last_name lastName, email, gender from tbl_employee where id = #{id}
</select>
</mapper>
3. 測試
使用 SqlSession 獲取映射器進行操作
@Test
public void test01() throws IOException{
// 1. 獲取sqlSessionFactory對象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2. 獲取sqlSession實例
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
// 3. 獲取接口的實現類對象
// Mybatis會爲接口自動的創建一個代理對象,由代理對象去執行增刪改查方法
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
// 4. 調用接口方法
Employee employee = mapper.getEmpById(1);
System.out.println(employee);
} finally {
sqlSession.close();
}
}
三、SqlSession
-
SqlSession和 connection 一樣,他們的實例不是線程安全的,因此是不能被共享的。
-
SqlSession每次使用完成後需要正確關閉,這個 關閉操作是必須的
-
SqlSession可以直接調用方法的id進行數據庫操 作,但是我們一般還是推薦使用接口式編程,SqlSession獲取 到Dao接口的代理類,執行代理對象的方法,可 以更安全的進行類型檢查操作
👉 👉 👉 MyBlog - 小牛肉的個人博客,歡迎來訪~👈 👈 👈