一、框架:
半成品,可以理解為房子的大框,之后砌墻會在其基礎(chǔ)上梆造。
二、簡介
MyBatis 本是[apache]的一個開源項(xiàng)目[iBatis], 2010年這個項(xiàng)目由apache software foundation 遷移到了google code葬毫,并且改名為MyBatis 镇辉。2013年11月遷移到Github。
iBATIS一詞來源于“internet”和“abatis”的組合贴捡,是一個基于Java的[持久層]框架忽肛。
Mybatis是一個持久層框架。代替JDBC技術(shù)完成與數(shù)據(jù)庫交互功能的框架烂斋,操作過程中屹逛,調(diào)用底層封裝好的API础废,代碼會被解析成JDBC源碼進(jìn)行功能實(shí)現(xiàn)。
三罕模、優(yōu)點(diǎn)
1评腺、基于SQL語法的,簡單易學(xué)淑掌。
2蒿讥、jdbc將sql語句寫在java語句中,屬于硬編碼抛腕,而框架把SQL語句被封裝在配置文件中芋绸,方便程序的維護(hù),降低程序的耦合度担敌。
3摔敛、程序調(diào)試方便。
4全封、jdbc需要將查詢結(jié)果映射到實(shí)體類中舷夺,而框架可以省去這一步驟,查詢即得到映射好的對象售貌。
四、框架的搭建:
創(chuàng)建一個普通的JAVA工程疫萤。
引入jar包
Mybatis-3.2.7.jar:Mybatis的核心jar包
Ojdbc14.jar:驅(qū)動Jar
Commons-logging-1.1.1.jar
Log4j.jar:記錄日志的jar
Log4j.properties 消息資源文件
3颂跨、在src中引入SqlMapConfig.xml文件(名字可隨便取,但慣例都叫此扯饶,之后會有專門的地方根據(jù)名字讀取文件)恒削,現(xiàn)在專門解釋一下該文件,文件后綴名時xml尾序,可擴(kuò)展標(biāo)記語言钓丰。
①
<?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">
是處理指令,能夠解析MyBatis元素
③根元素
<configuration></configuration>
一個配置文件只能有一個根元素
④在<configuration></configuration>中配置數(shù)據(jù)源每币,所謂數(shù)據(jù)源就是數(shù)據(jù)的來源携丁,可以理解為數(shù)據(jù)庫
<environments default="oracle">
<environment id="oracle">
<!-- 事務(wù)管理器 -->
<transactionManager type="jdbc"></transactionManager>
<!-- 配置數(shù)據(jù)源 -->
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL"/>
<property name="username" value="scott"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
a.default中的值決定具體使用哪一數(shù)據(jù)源,所謂數(shù)據(jù)源就是數(shù)據(jù)的來源兰怠,即數(shù)據(jù)庫
b.在指定的數(shù)據(jù)源中梦鉴,首先配置事務(wù)控制器
c.配置數(shù)據(jù)源的相關(guān)信息,POOLED表示使用連接池進(jìn)行連接
d.property中的name都有特定的含義揭保,不允許改變
4肥橙、建表語句
-- Create table
create table T_USER
(
id NUMBER not null,
username VARCHAR2(20),
hiredate DATE,
password VARCHAR2(20)
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table T_USER
add constraint PK_T_USER_ID primary key (ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
創(chuàng)建實(shí)體類
public class User {
private int id;
private String username;
private String password;
private Date hiredate;
}
5、創(chuàng)建接口UserMapper
public interface UserMapper {
User getUser(int id);
}
6秸侣、創(chuàng)建與UserMapper接口同名的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">
<!-- namespace命名空間存筏,作用就是對sql進(jìn)行分類化管理-->
<mapper namespace="com.dao.UserMapper">
<select id="getUser" parameterType="java.lang.Integer" resultType="com.bean.User">
select * from t_user where id = #{value}
</select>
</mapper>
①mapper是根元素
②<mapper namespace="com.dao.UserMapper">的namespace值必須寫接口的全限定名宠互,
③根元素中可以編寫sql語句
④parameterType:指定輸入?yún)?shù)類型,mybatis 從輸入對象中獲取參數(shù)值拼接在 sql 中椭坚。
resultType:指定輸出結(jié)果類型予跌,mybatis 將 sql 查詢結(jié)果的一行記錄數(shù)據(jù)映射為 resultType 指定類型的對象。
上述參數(shù)值需要引入全限定名
7藕溅、有的童鞋可能猜到了匕得,你可以認(rèn)為這個配置文件類似于接口的實(shí)現(xiàn)類,只不過我們不用implements關(guān)鍵字巾表,而是在主配置文件中讀取它
<environments default="oracle">
</environments>
<mappers>
<!-- <mapper resource="com/dao/UserMapper.xml"/> -->
<package name="com.dao"/>
</mappers>
8最后汁掠,我們編寫測試類,主要經(jīng)過如下步驟
①加載核心配置文件
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
②獲取數(shù)據(jù)庫連接池對象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
③獲取與數(shù)據(jù)庫的鏈接
SqlSession session = factory.openSession();
④通過連接拿到實(shí)體類對象
UserMapper userMapper = session.getMapper(UserMapper.class);
此時相關(guān)數(shù)據(jù)已經(jīng)封裝給了實(shí)體類
五集币、引入配置文件
在classpath下創(chuàng)建db.properties
jdbc.driver =oracle.jdbc.driver.OracleDriver
jdbc.url = jdbc:oracle:thin:@localhost:1521:neuedu
jdbc.username=scott
jdbc.password=tiger
此時在SqlMapConfig.xml文件中需要修改為
<!-- properties元素:
resource屬性考阱,要引入的消息資源文件相對于src的路徑 -->
<properties resource="db.properties"></properties>
<environments default="oracle">
<environment id="oracle">
<!-- 事務(wù)管理器 -->
<transactionManager type="jdbc"></transactionManager>
<!-- 配置數(shù)據(jù)源 -->
<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>
六、關(guān)于Mybatis的API
1鞠苟、SqlSession
SqlSession 中封裝了對數(shù)據(jù)庫的操作乞榨,如:查詢、插入当娱、更新吃既、刪除等。
2跨细、SqlSessionFactoryBuilder
SqlSessionFactoryBuilder 用于創(chuàng)建 SqlSessionFacoty鹦倚,SqlSessionFacoty 一旦創(chuàng)建完成就不需要SqlSessionFactoryBuilder 了,因?yàn)?SqlSession 是通過 SqlSessionFactory 生產(chǎn)冀惭,所以可以將SqlSessionFactoryBuilder 當(dāng)成一個工具類使用震叙,最佳使用范圍是方法范圍即方法體內(nèi)局部變量。
3散休、SqlSessionFactory
SqlSessionFactory 是一個接口媒楼,接口中定義了 openSession 的不同重載方法,SqlSessionFactory 的最佳使用范圍是整個應(yīng)用運(yùn)行期間戚丸,一旦創(chuàng)建后可以重復(fù)使用划址,通常以單例模式管理 SqlSessionFactory。
public class SqlSessionFactoryUtil {
//首先創(chuàng)建靜態(tài)成員變量sqlSessionFactory限府,靜態(tài)變量被所有的對象所共享猴鲫。
public static SqlSessionFactory sqlSessionFactory = null;
public static SqlSessionFactory getSqlSessionFactory() {
//如果sqlSessionFactory沒有被創(chuàng)建就讀取全局配置文件,假如已經(jīng)被創(chuàng)建過了谣殊,就使用已經(jīng)存在的sqlsessionfactory拂共。
//這樣就有了單例模式的效果
if(sqlSessionFactory==null){
String resource = "SqlMapConfig.xml";
try {
Reader reader = Resources.getResourceAsReader(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return sqlSessionFactory;
}
}
七、類別名
1姻几、以上提到宜狐,在xml文件中配置SQL語句時势告,需要使用全限定名,因此非常不便抚恒,需要配置類別名咱台,使用typeAliases元素
<typeAliases>
<!-- typeAlias元素
type,全限定名
alias俭驮,類別名
-->
<typeAlias alias="User" type="com.bean.User"/>
</typeAliases>
此時查詢就可以使用User代替com.bean.User回溺,注意,該元素必須在environments元素以前寫混萝,因?yàn)閤ml文件對元素順序有要求
2遗遵、內(nèi)置別名
java中的類型可以直接使用,無需配置別名逸嘀,如int,long,String,List,Map
八车要、核心配置文件
1、defualt屬性
現(xiàn)在崭倘,讓我們來說一說environments元素的default屬性翼岁,這是一個必須有的屬性,由于系統(tǒng)可能配置多個數(shù)據(jù)源司光,因此需要指定一個默認(rèn)數(shù)據(jù)源琅坡,default的值與environment的id相對應(yīng),那就走該id所在的數(shù)據(jù)源
<environments default="oracle">
<environment id="oracle">
</environment>
<environment id="oracle1">
</environment>
</environments>
還有一種情況残家,若我default的值指定了某一個數(shù)據(jù)源榆俺,是不是就連不了別的數(shù)據(jù)源?答案是否定的跪削,SqlSessionFactoryBuilder有一個重載的方法能夠指定連接其他數(shù)據(jù)源,如下代碼所示
<environments default="oracle">
<environment id="oracle">
</environment>
<environment id="oracle1">
<transactionManager type="jdbc"></transactionManager>
<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="kkk"/>
</dataSource>
</environment>
</environments>
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader,"oracle1");
由于我在oracle1中密碼錯誤迂求,因此登錄失敗
2碾盐、事務(wù)管理器transactionManager
type屬性,指定事務(wù)管理方式揩局,可選值有
jdbc:利用傳統(tǒng)jdbc方式進(jìn)行事務(wù)處理毫玖,需要手動提交、回滾
MANAGED:讓容器進(jìn)行事務(wù)處理凌盯,此處容器指Spring容器付枫,若配成此選項(xiàng),意味著Mybatis不進(jìn)行事務(wù)管理驰怎,交給Spring
3阐滩、dataSource元素
type屬性,指定配置數(shù)據(jù)源連接的方式县忌,可選擇的值如下
POOLED,使用數(shù)據(jù)庫連接池掂榔,使用能夠存放多個已經(jīng)生成好的數(shù)據(jù)庫連接的區(qū)域继效,好處在于想拿連接時只需要open一下就可以拿到連接,不涉及對連接的管理
UNPOOLED装获,不使用數(shù)據(jù)庫連接池瑞信,即使用原始連接方式,需要對連接管理
JNDI穴豫,使用第三方數(shù)據(jù)庫連接池凡简,POOLED表示使用Mybatis自己的連接池,如果想使用第三方精肃,就選這一項(xiàng)秤涩,常見提供數(shù)據(jù)庫連接池的第三方有tomcat自帶的連接池,Spring容器
4肋杖、mappers
將應(yīng)用中所有SQL映射文件配置到核心配置文件中溉仑,目的是加載核心配置文件時能夠加載SQL映射文件,xml文件與以往java文件不同状植,java文件編譯成字節(jié)碼后浊竟,其他方法就可以調(diào)用其中的方法,想用xml文件必須加載
5津畸、其他元素
如settings振定,可以用來優(yōu)化配置,最多可以連幾個連接肉拓,或同時最多可以執(zhí)行幾個SQL語句后频,幾乎不常用,而且真正開發(fā)時也不需要你去做
九暖途、SQL映射文件
我們之前拿最簡單的查詢做了例子演示框架搭建卑惜,現(xiàn)在,讓我們看一下復(fù)雜的查詢以及增刪改如何去做驻售,一般情況下露久,我們都是一個SQL映射文件對應(yīng)一張表和一個實(shí)體類,有關(guān)該實(shí)體類的增刪改查都在同一個映射文件中
1欺栗、回顧一下最簡單的查詢
select元素相關(guān)屬性
id,必須存在的屬性毫痕,值從概念上講是唯一標(biāo)示,不能隨便寫迟几,應(yīng)對應(yīng)接口中方法的名
parameterType消请,若該方法有參,則必須有該屬性类腮,值和接口中參數(shù)的類型相對應(yīng)
resultType臊泰,結(jié)果集的類型,經(jīng)過查詢蚜枢,數(shù)據(jù)庫中的信息自動封裝因宇,指定類型七婴,就告訴框架你把信息封裝成一個什么類型的對象
2、多個參數(shù)
需求:根據(jù)用戶名和編號進(jìn)行查詢
接口中增加方法
User selectUser(String username,int id);
發(fā)現(xiàn)parameterType無法指定類型察滑,
①加注解
User selectUser(@Param("username")String username,@Param("id")int id);
<select id="selectUser" resultType="User">
select * from t_user where username = #{username} and id = #{id}
</select>
②參數(shù)整合在一起打厘,使用bean對象,
List<User> selectUser(User user);
<select id="selectUser" parameterType="User" resultType="User">
select * from t_user where username = #{username} and id = #{id}
</select>
注意,查詢結(jié)果有多條贺辰,使用list集合作為返回值類型户盯,resultType指定集合中元素的類型
3、刪除
需求:根據(jù)id進(jìn)行刪除
void deleteUser(int id);
<delete id="deleteUser" parameterType="int">
delete from t_user where id = #{value}
</delete>
去測試類中執(zhí)行發(fā)現(xiàn)并沒有生效饲化,沒有自動提交莽鸭,因此需要在try中調(diào)用session的commit方法,在catch中調(diào)用session的rollback方法
4吃靠、修改
void updateUser(User user);
<update id="updateUser" parameterType="User">
update t_user set username = #{username},password = #{password}
where id = #{id}
</update>
5硫眨、插入
<!-- keyProperty屬性主鍵列對應(yīng)的屬性的名稱
order屬性BEFORE表示子查詢在主查詢前
-->
<insert id="insertUser">
insert into t_user values(#{id},#{username},sysdate,#{password})
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select max(id)+1 from t_user
</selectKey>
</insert>
void insertUser(User user);
User user = new User();
user.setUsername("k");
user.setPassword("k");
userMapper.insertUser(user);
session.commit();
十、特殊結(jié)果巢块、參數(shù)
1礁阁、特殊參數(shù)類型使用
根據(jù)用戶名和密碼查詢,比如此時用戶名和密碼不同時寫在同一個實(shí)體類中族奢,此時要使用一個參數(shù)就要用到Map
User selectUserByNAP(Map<String,String> map);
<select id="selectUserByNAP" parameterType="map" resultType="User">
select * from t_user where username = #{m_username} and password = #{m_password}
</select>
Map<String,String> map = new HashMap<String,String>();
map.put("m_username", "l");
map.put("m_password", "l");
User user = userMapper.selectUserByNAP(map);
System.out.println(user.getPassword());
sql語句中參數(shù)等于Map的鍵
2姥闭、特殊結(jié)果集使用
如果實(shí)體類屬性與數(shù)據(jù)庫列名不一樣,就使用resultMap作為結(jié)果集類型
User selectUserByNAP1(Map<String,String> map);
<select id="selectUserByNAP1" parameterType="map" resultMap="userres">
select * from t_user where username = #{m_username} and password = #{m_password}
</select>
<resultMap type="User" id="userres">
<result column="password" property="password"></result>
</resultMap>
Map<String,String> map = new HashMap<String,String>();
map.put("m_username", "l");
map.put("m_password", "l");
User user = userMapper.selectUserByNAP1(map);
System.out.println(user.getPassword());
type:查詢結(jié)果最終得到的類型
3越走、建employee和department兩張表棚品,其中employee表有eid、eno廊敌、ename铜跑、deptid等字段,department表有did骡澈、dno锅纺、dname等字段
-- Create table
create table T_DEPARTMENT
(
did NUMBER(4) not null,
dno VARCHAR2(20),
dname VARCHAR2(20)
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table T_DEPARTMENT
add constraint PK_DID_DEPARTMENT primary key (DID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
-- Create table
create table T_EMPLOYEE
(
eid NUMBER(4) not null,
eno VARCHAR2(20),
ename VARCHAR2(20),
deptid NUMBER(4)
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table T_EMPLOYEE
add constraint PK_EID_EMPLOYEE primary key (EID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
alter table T_EMPLOYEE
add constraint FK_DEPTID_EMPLOYEE foreign key (DEPTID)
references T_DEPARTMENT (DID);
public class Employee {
private int eid;
private String eno;
private String ename;
private Department dept;
}
public class Department {
private int did;
private String dno;
private String dname;
private List<Employee> employees;
}
十一、多表查詢
1秧廉、一對一關(guān)聯(lián)
如果要做查詢員工信息同時將部門信息同時查出來
(1)嵌套子查詢
public Employee getEmployeeById(int eid);
<select id="getEmployeeById" parameterType="int" resultMap="empres">
select * from t_employee where eid = #{eid}
</select>
<!-- 嵌套子查詢
association元素
property屬性嵌套查詢的結(jié)果賦值給Employee中屬性的名字
column屬性外鍵字段的名稱
javaType屬性嵌套子查詢返回結(jié)果集的類型
select屬性嵌套的子查詢對相應(yīng)查詢
-->
<resultMap type="Employee" id="empres">
<association property="dept" column="deptid" javaType="Department" select="getDeptById"></association>
</resultMap>
<select id="getDeptById" parameterType="int" resultType="Department">
select * from t_department where did = #{deptid}
</select>
association元素
property屬性嵌套查詢的結(jié)果賦值給Employee中屬性的名字
column屬性外鍵字段的名稱
javaType屬性嵌套子查詢返回結(jié)果集的類型
select屬性嵌套的子查詢對相應(yīng)查詢
以上查詢的做法實(shí)際上非常不好伞广,僅做了一個多表查詢就需要多次操作數(shù)據(jù)庫
(2)嵌套結(jié)果
public Employee getEmployeeByNo(String eno);
<select id="getEmployeeByNo" parameterType="string" resultMap="empRes">
select *
from t_employee e,t_department d
where e.deptid = d.did
and e.eno = #{eno}
</select>
<resultMap type="employee" id="empRes">
<association property="dept" column="deptid" javaType="Department" resultMap="deptRes"></association>
</resultMap>
<resultMap type="department" id="deptRes">
<result property="did" column="did"></result>
<result property="dno" column="dno"></result>
<result property="dname" column="dname"></result>
</resultMap>
EmployeeDao employeeDao = session.getMapper(EmployeeDao.class);
Employee employee = employeeDao.getEmployeeByNo("1");
System.out.println(employee.getDept().getDid());
2拣帽、一對多關(guān)聯(lián)
查詢部門信息疼电,并將該部門所有員工查詢出來
Department getDepartmentById(int did);
<select id="getDepartmentById" parameterType="int" resultMap="deptRes">
select *
from t_employee e,t_department d
where e.deptid = d.did
and d.did = #{did}
</select>
<resultMap type="department" id="deptRes">
<result property="did" column="did"></result>
<result property="dno" column="dno"></result>
<result property="dname" column="dname"></result>
<!-- 一對多的關(guān)聯(lián)查詢
collection元素
property屬性針對多個員工信息封裝出的集合容器類型的對象,賦值給department類中的對應(yīng)的屬性
ofType屬性集合中每個元素的類型 -->
<collection property="employees" ofType="employee">
<result property="eid" column="eid"></result>
<result property="eno" column="eno"></result>
<result property="ename" column="ename"></result>
</collection>
</resultMap>
DepartmentDao departmentDao = session.getMapper(DepartmentDao.class);
Department department = departmentDao.getDepartmentById(1);
List<Employee> list = department.getEmployees();
System.out.println(list.get(0).getEid());
3减拭、向員工表中插入一條數(shù)據(jù)蔽豺,同時指定其部門信息
<insert id="insert" parameterType="employee">
insert into t_employee values (#{eid},#{eno},#{ename},#{dept.did})
<selectKey keyProperty="eid" resultType="int" order="BEFORE">
select max(eid)+1 from t_employee
</selectKey>
</insert>
void insert(Employee e);
Employee employee = new Employee();
employee.setEno("2");
employee.setEname("Lily");
Department department = new Department();
department.setDid(1);
employee.setDept(department);
EmployeeDao employeeDao = session.getMapper(EmployeeDao.class);
employeeDao.insert(employee);
session.commit();
4、分頁查詢
利用pageHelper插件
首先引入jar包
jsqlparser-0.9.jar
pagehelper-3.6.4.jar
在核心配置文件中加入
<!-- plugins元素加在typeAliases下 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- property元素指明和哪個數(shù)據(jù)庫匹配使用 -->
<property name="dialect" value="oracle"></property>
</plugin>
</plugins>
在查詢映射文件中加入
<select id="getAll" resultType="user">
select * from t_user
</select>
List<User> getAll();
//獲取第一頁數(shù)據(jù)拧粪,每頁顯示1條
Page page = PageHelper.startPage(1, 1);
userMapper.getAll();
System.out.println("共"+page.getTotal()+"條記錄");
List<User> list = page.getResult();
for(User u:list){
System.out.println(u.getPassword());
}
5修陡、組合查詢
<!-- 條件查詢where元素沧侥,補(bǔ)齊where關(guān)鍵字 -->
<select id="getByCondition" parameterType="user" resultType="user">
select * from t_user
<!-- where 1=1 -->
<where>
<if test="id != null and id != 0">
and id = #{id}
</if>
<if test="username != null and username != ''">
and username = #{username}
</if>
</where>
</select>
6、批量刪除
<!-- 參數(shù)是數(shù)組魄鸦,無需加參數(shù)
foreach元素遍歷集合容器對象
collection屬性指定的是方法傳入的類型
item屬性每次遍歷到的元素
open屬性遍歷得到的結(jié)果的開始字符
separator屬性元素之間的分隔符
-->
<delete id="deleteUsers">
delete from t_user where id in
<foreach collection="array" item="item" open="(" close=")" separator=",">
#{item}
</foreach>
</delete>
void deleteUsers(int[] ids);
int[] i = new int[2];
i[0] = 3;
i[1] = 4;
userMapper.deleteUsers(i);
session.commit();
7宴杀、緩存
User user = userMapper.getUser(1);
user.setPassword("k");
//修改查詢到的user信息
System.out.println(user.getPassword());
user.setPassword("j");
//再次查詢理論上應(yīng)該得到數(shù)據(jù)庫中的內(nèi)容,但是卻是上述修改后的內(nèi)容拾因,這是因?yàn)镸ybatis緩存
//緩存是因?yàn)樘岣咝阅? user = userMapper.getUser(1);
System.out.println(user.getPassword());
此時需要在sql映射文件中加入flushCache="true"
<select id="getUser" parameterType="java.lang.Integer" resultType="User" flushCache="true">
select * from t_user where id = #{value}
</select>
當(dāng)查詢數(shù)據(jù)庫返回結(jié)果時旺罢,mybatis會生成key、value形式的對象存在于緩存绢记,在接下來在內(nèi)存中針對查詢結(jié)果做變更扁达,相當(dāng)于改變了緩存中的數(shù)據(jù),再次查詢不訪問數(shù)據(jù)庫蠢熄,而是直接采用緩存中的數(shù)據(jù)