首先導包
依賴如下
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
構建SqlSessionFactory
MyBatis應用是以SqlSessionFactory爲中心的,實例可以通過SqlSessionFactoryBuilder獲得.
其中SqlSessionFactory是工廠接口,任務用於創建SqlSession
配置文件將會解析配置XML文件在Configuration類對象中.
配置XML獲取數據源,事務管理器,映射器
在resource文件下新建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>
<!-- 定義別名 -->
<typeAliases>
<typeAlias type="com.ming.Role" alias="role"/>
</typeAliases>
<!-- 定義數據庫信息 -->
<environments default="development">
<environment id="development">
<!-- jdbc事物管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 數據庫鏈接信息 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://47.94.95.84:32786/mybatis"/>
<property name="username" value="mybatis"/>
<property name="password" value="ABCcba20170607"/>
</dataSource>
</environment>
</environments>
</configuration>
新建類
package com.ming;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class Role {
public String getSqlSessionFactory(){
String resource = "mybatis-config.xml";
try {// 獲得輸入流
InputStream inputStream;
inputStream = Resources.getResourceAsStream(resource);
// 獲得SqlSessionFactory工廠
SqlSessionFactory sqlSessionFactory = null;
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e){
e.printStackTrace();
}
return null;
}
}
最後新建測試類
package com.ming;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class RoleTest {
private Role role = null;
@Before
public void setUp() throws Exception {
this.role = new Role();
}
@After
public void tearDown() throws Exception {
}
@Test
public void getSqlSessionFactory() {
role.getSqlSessionFactory();
}
}
此時的目錄結構
代碼方式構建
public SqlSessionFactory getSqlSessionFactory1(){
// 創建數據庫連接池
PooledDataSource dataSource = new PooledDataSource();
dataSource.setDriver("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://47.94.95.84:32786/mybatis");
dataSource.setUsername("mybatis");
dataSource.setPassword("ABCcba20170607");
// 構建數據庫事物
TransactionFactory transactionFactory = new JdbcTransactionFactory();
// 創建數據庫環境
Environment environment = new Environment("development", transactionFactory, dataSource);
// 構建Configuration對象
Configuration configuration = new Configuration(environment);
// 註冊上下文別名
configuration.getTypeAliasRegistry().registerAlias("role", Role.class);
// 創建映射器
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
return sqlSessionFactory;
}
書寫測試用例如下
package com.ming;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class RoleTest {
private Role role = null;
@Before
public void setUp() throws Exception {
this.role = new Role();
}
@After
public void tearDown() throws Exception {
}
@Test
public void getSqlSessionFactory() {
role.getSqlSessionFactory();
}
@Test
public void getSqlSessionFactory1() {
role.getSqlSessionFactory1();
}
}
創建SqlSession
SqlSession屬於門面,通過SqlSession可以獲得需要的什麼信息
SqlSession sqlSession = null;
try{
// 創建一個sqlsession會話
sqlSession = sqlSessionFactory.openSession();
sqlSession.commit();
}catch (Exception e){
// 輸出錯誤信息
System.out.println(e.getMessage());
// 進行事物操作,回滾數據庫數據
sqlSession.rollback();
}finally {
// 進行資源關閉
if(sqlSession != null){
sqlSession.close();
}
}
SqlSession作用,獲取映射器,通過命名信息執行sql結果
映射器
映射器由java和xml文件共同組成,作用
定義參數類型
描述緩存
描述sql
定義查詢結果和POJO映射關係
先給出java接口
package com.ming;
public interface RoleMapper {
public Role getRole(Long id);
}
根據給定的id獲取角色對象
給出映射文件,然後在生成的時候會根據接口實現類,生成對象.
先編寫POJO
package com.ming;
// POJO
public class Role {
private int id;
private String roleName;
private String note;
public void setId(int id) {
this.id = id;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public void setNote(String note) {
this.note = note;
}
public int getId() {
return id;
}
public String getRoleName() {
return roleName;
}
public String getNote() {
return note;
}
}
在編寫映射配置文件
<?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.ming.RoleMapper">
<!-- 定義的接口方法爲getRole 類型參數爲long 返回的結果爲role 即之前定義在xml文件中定義的vo別名 -->
<select id="getRole" parameterType="int" resultType="role">
<!-- 定義sql語句-->
SELECT id, role_name as roleName, note FROM t_role WHERE id = #{id}
</select>
</mapper>
最後編寫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 type="com.ming.Role" alias="role"/>
</typeAliases>
<!-- 定義數據庫信息 -->
<environments default="development">
<environment id="development">
<!-- jdbc事物管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 數據庫鏈接信息 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://47.94.95.84:32786/mybatis"/>
<property name="username" value="mybatis"/>
<property name="password" value="ABCcba20170607"/>
</dataSource>
</environment>
</environments>
<!-- 定義映射器 -->
<mappers>
<mapper resource="RoleMapper.xml"></mapper>
</mappers>
</configuration>
最後再編寫執行sql的類
package com.ming;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import java.io.IOException;
import java.io.InputStream;
public class MyBatis {
public String getSqlSessionFactory(){
String resource = "mybatis-config.xml";
SqlSessionFactory sqlSessionFactory = null;
try {// 獲得輸入流
InputStream inputStream;
inputStream = Resources.getResourceAsStream(resource);
// 獲得SqlSessionFactory工廠
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e){
e.printStackTrace();
}
SqlSession sqlSession = null;
try{
// 創建一個sqlsession會話
sqlSession = sqlSessionFactory.openSession();
// 獲得映射器
// 接口傳入映射器中
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
// 執行方法
Role role = roleMapper.getRole(0);
System.out.println(role.getRoleName());
// 刷新語句並提交鏈接
sqlSession.commit();
}catch (Exception e){
// 輸出錯誤信息
System.out.println(e.getMessage());
// 進行事物操作,回滾數據庫數據
sqlSession.rollback();
}finally {
// 進行資源關閉
if(sqlSession != null){
sqlSession.close();
}
}
return null;
}
public SqlSessionFactory getSqlSessionFactory1(){
// 創建數據庫連接池
PooledDataSource dataSource = new PooledDataSource();
dataSource.setDriver("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://47.94.95.84:32786/mybatis");
dataSource.setUsername("mybatis");
dataSource.setPassword("ABCcba20170607");
// 構建數據庫事物
TransactionFactory transactionFactory = new JdbcTransactionFactory();
// 創建數據庫環境
Environment environment = new Environment("development", transactionFactory, dataSource);
// 構建Configuration對象
Configuration configuration = new Configuration(environment);
// 註冊上下文別名
configuration.getTypeAliasRegistry().registerAlias("role", MyBatis.class);
// 創建映射器
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
return sqlSessionFactory;
}
}
最後編寫測試類
package com.ming;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class MyBatisTest {
private MyBatis myBatis = null;
@Before
public void setUp() throws Exception {
this.myBatis = new MyBatis();
}
@After
public void tearDown() throws Exception {
}
@Test
public void getSqlSessionFactory() {
myBatis.getSqlSessionFactory();
}
@Test
public void getSqlSessionFactory1() {
myBatis.getSqlSessionFactory1();
}
}
執行單元測試
結果如下
即完成了MyBatis的一次查詢
註解
定義接口
package com.ming;
import org.apache.ibatis.annotations.Select;
public interface Role1 {
@Select (value="SELECT id, role_name as roleName, note FROM t_role WHERE id = #{id}")
public Role getRole(int id);
}
生命週期
SqlSessionFactoryBuilder
其是利用xml或者java編碼構建SqlSessionFactory 可以構建多個SessionFactory 作用 構建器
根據構建器獲得sqlSessionFactory
SqlSessionFactory
創建SqlSession 一個SqlSession相當於JDBC的Connection對象
此爲單例管理
每創建一個SqlSession就會創建一個數據庫連接
SqlSession
此爲一個會話,相當於一個Connection連接 線程不安全
生命週期爲一個應用的請求和操作,可以執行多條sql