一、MyBatis的HelloWord
1.根據xml配置文件(全局配置文件mybatis-config.xml)創建一個SqlSessionFactory對象 有數據源一些運行環境信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<?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= "123456" /> </dataSource> </environment> </environments> <!-- 將我們寫好的sql映射文件(EmployeeMapper.xml)一定要注冊到全局配置文件(mybatis-config.xml)中 --> <mappers> <mapper resource= "EmployeeMapper.xml" /> </mappers> </configuration> |
2.sql映射文件EmployeeMapper.xml;配置了每一個sql,以及sql的封裝規則等。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?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.atguigu.mybatis.dao.EmployeeMapper" > <!-- namespace:名稱空間;指定為接口的全類名 id:唯一標識 resultType:返回值類型 #{id}:從傳遞過來的參數中取出id值 public Employee getEmpById(Integer id); 分離實現與接口 --> <select id= "getEmpById" resultType= "com.atguigu.mybatis.bean.Employee" > select id,last_name lastName,email,gender from tbl_employee where id = #{id} </select> </mapper> |
3.將sql映射文件注冊在全局配置文件mybatis-config.xml中
1
2
3
|
<mappers> <mapper resource= "EmployeeMapper.xml" /> </mappers> |
4.寫代碼:
1).根據全局配置文件得到SqlSessionFactory;
1
2
3
|
String resource = "mybatis-config.xml" ; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); |
2).使用sqlSession工廠,獲取到sqlSession對象使用他來執行增刪改查,一個sqlSession就是代表和數據庫的一次會話,用完關閉
1
|
SqlSession openSession = sqlSessionFactory.openSession(); |
3).使用sql的唯一標志來告訴MyBatis執行哪個sql。sql都是保存在sql映射文件中的
1
2
3
4
5
6
7
|
try { Employee employee = openSession.selectOne( "com.atguigu.mybatis.dao.EmployeeMapper.getEmpById" , 1 ); // spacename + sqlId System.out.println(employee); } finally { openSession.close(); } |
二、MyBatis接口式編程
1
|
mybatis: Mapper.java(接口) ====> xxMapper.xml(實現) |
接口式編程的好處在于,能夠將功能與實現相分離
1、SqlSession代表和數據庫的一次會話;用完必須關閉;
2、SqlSession和connection一樣它都是非線程安全。每次使用都應該去獲取新的對象。
3、mapper.java接口沒有實現類,但是mybatis會為這個接口生成一個代理對象。(將接口和xml進行綁定)
EmployeeMapper empMapper = sqlSession.getMapper(EmployeeMapper.class);
4、兩個重要的配置文件:
- mybatis的全局配置文件:包含數據庫連接池信息,事務管理器信息等…系統運行環境信息
- sql映射文件:保存了每一個sql語句的映射信息:將sql抽取出來。
到此這篇關于初次體驗MyBatis的注意事項的文章就介紹到這了,更多相關MyBatis的用法內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/Wang_Pro/article/details/118110119