互聯網持久層框架Mybatis系列學習筆記
認識Mybatis的核心組件
1.1持久層的概念及Mybatis特點
持久層可以將業務數據轉存到磁盤,在重啓系統或者系統斷電後,這些數據依然能被再次讀取。一般執行持久層任務的都是數據庫管理系統,持久層可以使用巨大的磁盤空間,缺點是,相對於內存數據,磁盤數據讀寫較慢。經常在網上見到的各種商家秒殺,又是怎麼實現的呢?秒殺對數據讀寫要求高,所以出現了一種東西,名字叫Redis,它的存儲介質是內存,可以高速讀寫。後面會有專題博文來分析Redis技術,這裏說說Mybatis的三個優點:1. 不屏蔽原生SQL語句。優化SQL能顯著提高數據的讀寫效率,對於複雜的業務,可以使用原生SQL語句,也可以調用編寫好的存儲過程。這一點,Hibernate是不支持原生SQL的。
2. Mybatis提供強大靈活的映射機制,方便Java開發者使用。這其實在說動態SQL功能,允許開發人員根據條件組裝SQL。有了它,再也不怕產品經理經常改需求了。
3. Mybatis提供了基於Mapper的接口編程。一個接口對應一個XML配置,便能創建一個映射器。基於接口編程,對接Spring的IOC也會方便很多。
1.2準備Mybatis環境
筆者建議是下載Mybatis.jar包後,最好將源代碼也拿到,現在附上一個官方Mybatis使用教程的PDF文檔, [歡迎大家點擊下載](https://download.csdn.net/download/qq_37040173/10757111)。對於剛入門的開發者來說,閱讀源代碼這事兒,先放一放吧,等能夠熟練使用這個框架了,或許時機更合適。對於配置環境這件事兒,網上教程很多,DRY原則,呵呵。
1.3Mybatis核心組件介紹
Mybatis核心組件有四個:SqlSessionFactoryBuilder(構造器)/SqlSessionFactory(工廠接口)/SqlSession(會話)/SQL Mapper(映射器).1.4SqlSessionFactory
使用Mybatis的第一步是創建一個SqlSessionFactory.首先是使用org.ibatis.session.Configuration類讀取配置信息,然後使用“建造者模式”,由接口SqlSessionFactoryBuilder的build()方法創建一個SqlSessionFactory。需要聲明的是,SqlSessionFactory是一個接口,不是類。它的默認實現類時DefaultSqlSessionFactory,這個是應用在單線程場景;SqlSessionManager是應用在多線程場景的
一般來說,可以讀取XML配置文件,然後進行創建;也可以通過java代碼,推薦使用XML方式。
14.1使用XML方式創建接口SqlSessionFactory
1.首先是基礎配置文件,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>
<!-- AliasName -->
<typeAlias type="com.bert.chapter3.pojo.Role" alias="role"/>
</typeAliases>
<!-- Database Environment Configuration -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&serverTimezone=UTC" />
<property name="username" value="YourName" />
<property name="password" value="YourPassword" />
</dataSource>
</environment>
</environments>
<!-- MapperConfigs -->
<mappers>
<mapper resource="com/bert/chapter3/mapper/RoleMapper.xml"/>
</mappers>
</configuration>
2.POJO類,Role
public class Role {
private Long id;
private String roleName;
private String note;
/** getter and setter **/
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String name) {
this.roleName = name;
}
public String getNote() {
return this.note;
}
}
3.RoleMapper接口定義
public interface RoleMapper {
public Role getRole(long id);
public int insertRole(Role role);
public int deleteRole(long id);
public int updateRole(long id);
public List<Role> findRoles(String roleName);
}
4.RoleMapper.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.bert.chapter3.mapper.RoleMapper">
<select id="getRole" parameterType="long" resultType="role">
select id,role_name as roleName,note from t_role where id = #{id}
</select>
<select id="findRoles" parameterType="String" resultType="role">
<bind name="pattern" value="'%' + roleName + '%'" />
select id,role_name as roleName,note from t_role
where role_name like #{pattern}
</select>
<insert id="insertRole" parameterType="role" >
insert into t_role(role_name,note) values(#{roleName},#{note})
</insert>
<delete id="deleteRole" parameterType="long" >
delete from t_role where id = #{id}
</delete>
<update id="updateRole" parameterType="long" >
update t_role set role_name=#{roleName},note=#{note} where id=#{id}
</update>
</mapper>
5.單例模式創建一個SqlSessionFactory和SqlSession(多線程)
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;
public class SqlSessionFactoryUtil {
//1.Ensure the single pattern
private final static Class<SqlSessionFactoryUtil> LOCK = SqlSessionFactoryUtil.class;
//2.Ensure sessionFactory is the only instance of the SqlSessionFactory
private static SqlSessionFactory sessionFactory = null;
//3.the constructor is privatized.
private SqlSessionFactoryUtil() {
;
}
//4.A singleton approach to public disclosure
public static SqlSessionFactory getSqlSessionFactory() {
synchronized (LOCK) {
if(sessionFactory != null) {
return sessionFactory;
}
String resource = "mybatis-config.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
//The Builder Pattern.
sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch(IOException e) {
e.printStackTrace();
return null;
}
return sessionFactory;
}
}
public static SqlSession openSqlSession() {
if(sessionFactory == null) {
getSqlSessionFactory();
}
return sessionFactory.openSession();
}
}
6.程序的入口Main類
public class Main {
public static void main(String [] args) {
Logger logger = Logger.getLogger(Main.class);
SqlSession sqlSession =null;
try {
sqlSession = SqlSessionFactoryUtil.openSqlSession();
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
Role role = roleMapper.getRole(3L);
logger.error(role.getRoleName());
System.out.println("--------------");
System.out.println(role.getId()+"---"+ role.getRoleName()+"-----"+role.getNote());
sqlSession .commit();
}catch(Exception e) {
sqlSession.rollback();
e.printStackTrace();
}
finally {
if(sqlSession != null) {
sqlSession.close();
}
}
System.out.println("I am in love with your body.");
}
}
第一篇介紹就寫到這裏,可能會有後續篇。
說一下我寫博客的感受吧。我覺得,這篇博客中的東西,沒什麼獨特性,也不一定能爲讀者帶來什麼幫助。我寫完之後,貌似也沒有對什麼概念理解得更加清楚,反之,我更像是一個搬運工,簡單的把知識從書本搬運到了這個博客,關鍵是花費了我一個上午的時間來整理這個博客。所以,以後再寫博客時,就不會像這樣寫了,,,,我又不是來寫教程的,現在是自顧不暇狀態,哪有時間和能力來分享我的學習經驗啊。
相反的,什麼東西是有用的呢?其實,我在寫代碼中間,會把遇到的錯誤Bug記錄到一個記事本文件中,同樣也會在旁邊寫下當時是怎麼解決的。。。。這個記事本的記錄,應該對大家和我都有用,而且內容也不多。咱們不能老是模仿着別人在寫這些表面博客,做實事兒更重要。下一次再有閒心了,不如貼出來Bug集合。