Mybatis-06 動態Sql
Mybatis系列文章已經完成上傳:
一、什么是Mybatis
二、CRUD
三、配置解析
四、日志、分頁
五、注解開發
六、動態Sql
多對一處理
多個學生,對應一個老師
對於學生這邊而言,關聯多個學生,關聯一個老師 【多對一】
對於老師而言,集合,一個老師又很多學生 【一對多】
1.創建數據庫


2.創建實體類
@Data
@NoArgsConstructor
@AllArgsConstructor
public class teacher {
private int id;
private String name;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class student {
private int id;
private String name;
private teacher teacher;
}
3.接口類
public interface StudentMapper {
public List<student> getStudent();
}
4.Mapper.xml文件
思路:
- 查詢出所有學生
- 根據tid查詢其對應老師
復雜的對象就用association
和collection
對象:association
集合:collection
4.1 按照查詢嵌套處理
<mapper namespace="com.Dao.StudentMapper">
<resultMap id="stutea" type="pojo.student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="pojo.teacher" select="getTeacher"/>
</resultMap>
<select id="getStudent" resultMap="stutea">
select * from mybatistest.stu
</select>
<select id="getTeacher" resultType="pojo.teacher">
select * from mybatistest.teacher where id = #{id}
</select>
</mapper>
4.2 按照結果嵌套處理
<mapper namespace="com.Dao.StudentMapper">
<select id="getStudent" resultMap="studentTeacher2">
select s.id,s.name,t.name
from mybatistest.stu s,mybatistest.teacher t
where s.tid=t.id
</select>
<resultMap id="studentTeacher2" type="pojo.student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" javaType="pojo.teacher">
<result property="name" column="name"/>
</association>
</resultMap>
</mapper>
5.測試
@Test
public void getStudent(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<student> student = mapper.getStudent();
for (pojo.student student1 : student) {
System.out.println(student1);
}
sqlSession.close();
}


一對多處理
數據庫不變
1.創建實體類
@Data
@NoArgsConstructor
@AllArgsConstructor
public class teacher {
private int id;
private String name;
private List<student> students;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class student {
private int id;
private String name;
// private teacher teacher;
private int tid;
}
2.接口類
public interface TeacherMapper {
public teacher getTeacher(@Param("tid") int id);
}
3.Mapper.xml文件
3.1 按照查詢嵌套處理
<mapper namespace="com.Dao.TeacherMapper">
<select id="getTeacher" resultMap="geTeacher" >
select * from mybatistest.teacher where id = #{tid}
</select>
<resultMap id="geTeacher" type="pojo.teacher">
<collection property="students" javaType="ArrayList" ofType="pojo.student" select="getStudent" column="id"></collection>
</resultMap>
<select id="getStudent" resultType="pojo.student">
select * from mybatistest.stu where tid = #{tid}
</select>
</mapper>
3.2 按照結果嵌套處理
<mapper namespace="com.Dao.TeacherMapper">
<select id="getTeacher" resultMap="teacherStudent">
select t.id tid,t.name tname,s.id sid,s.name sname
from mybatistest.stu s,mybatistest.teacher t
where s.tid=t.id and t.id=#{tid}
</select>
<resultMap id="teacherStudent" type="pojo.teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="pojo.student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
</mapper>
4.測試
@Test
public void getTeacher(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}


ofType & javaType
javaType
用來指定實體類中屬性ofTyoe
用來指定映射到List或者集合中pojo類型,泛型中的約束類型
注意點:注意一對多和多對一中,屬性名和字段的問題
動態sql
動態SQL就是指根據不同的條件生成不同的SQL語句
- If
- choose (when, otherwise)
- trim (where, set)
- foreach
1.基礎准備
1.1 創建數據庫
CREATE TABLE `blog`(
`id` INT(10) NOT NULL COMMENT '博客id',
`title` VARCHAR(20) NOT NULL COMMENT '博客標題',
`author` VARCHAR(10) NOT NULL COMMENT '作者',
`create_time` DATETIME NOT NULL COMMENT '創建時間',
`views` INT(20) NOT NULL COMMENT '瀏覽量'
)ENGINE=INNODB CHARSET=utf8;

1.2 創建實體類
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
1.3 創建接口類
public interface BlogMapper {
public int addBlog(Blog blog);
}
1.4 創建Mapper.xml文件
<mapper namespace="com.Dao.BlogMapper">
<insert id="addBlog" parameterType="pojo.Blog">
insert into mybatistest.blog(id,title,author,create_time,views)
values (#{id},#{title},#{author},#{createTime},#{views})
</insert>
</mapper>
1.5 測試代碼
@Test
public void Test(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog(1, "title", "張", new Date(), 11);
int i = mapper.addBlog(blog);
System.out.println(i);
}
2.IF
接口
public interface BlogMapper {
public List<Blog> queryBlogIF(Map map);
}
映射文件
<mapper namespace="com.Dao.BlogMapper">
<select id="queryBlogIF" parameterType="map" resultType="pojo.Blog">
select * from mybatistest.blog where 1=1
<if test="views != null">
and views > #{views}
</if>
<if test="author != null">
and author=#{author}
</if>
<if test="title != null">
and title like #{title}
</if>
</select>
</mapper>
測試
@Test
public void queryBlogIF(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("views",10);
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}

注意:
- 未綁定mapper
在配置文件中綁定:
<mappers>
<mapper class="com.Dao.BlogMapper"/>
</mappers>
- createTime數據為null
這是因為在實體類中,數據庫中定義時間屬性為:create_time,有_
。
可以開啟駝峰命名法映射,在配置文件中加入:
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
在數據庫字段命名規范中常常用下划線 "_" 對單詞進行連接,如:"create_time"
,而開發中實體屬性通常會采用駝峰命名法命名為 createTime
。
3.choose (when, otherwise)
接口
public interface BlogMapper {
public List<Blog> queryBlogChoose(Map map);
}
映射文件
<select id="queryBlogChoose" parameterType="map" resultType="pojo.Blog">
select * from mybatistest.blog
<where>
<choose>
<when test="title != null">
and title like #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views > #{views}
</otherwise>
</choose>
</where>
</select>
測試
@Test
public void queryBlogChoose(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title","%啦%");
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}

4.trim (where, set)
where
元素只會在子元素返回任何內容的情況下才插入 “WHERE” 子句。而且,若子句的開頭為 AND
或 OR
,where 元素也會將它們去除。
<where>
<if test="views != null">
views > #{views}
</if>
<if test="author != null">
and author=#{author}
</if>
<if test="title != null">
and title like #{title}
</if>
</where>
set
元素可以用於動態包含需要更新的列,忽略其它不更新的列。
接口
public int updateBlogSet(Map map);
映射文件
<update id="updateBlogSet" parameterType="map">
update mybatistest.blog
<set>
<if test="title != null">title=#{title},</if>
<if test="author != null">author=#{author},</if>
<if test="views != null">views=#{views},</if>
</set>
where id=#{id}
</update>
測試
@Test
public void updateBlogSet(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("id",1);
map.put("title","t-test");
map.put("author","a-test");
map.put("views",100);
int i = mapper.updateBlogSet(map);
System.out.println(i);
HashMap map1 = new HashMap();
List<Blog> blogs = mapper.queryBlogIF(map1);
for (Blog blog : blogs) {
System.out.println(blog);
}
}

5.Foreach
接口
public List<Blog> queryBlogForeach(Map map);
映射文件
<select id="queryBlogForeach" parameterType="map">
select * from mybatistest.blog
<where>
/*此處的collection是一個list,所以map需要傳入一個list來進行遍歷*/
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
<if test="views != null">
and views > #{views}
</if>
<if test="author != null">
and author=#{author}
</if>
</where>
</select>
測試
@Test
public void queryBlogForeach(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
List<Integer> ids = new ArrayList<Integer>();
ids.add(2);
ids.add(3);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}

6.Sql片段
我們可以將一些公共的部分用<sql>
抽取出來,方便復用!
<sql id="id-test">
<choose>
<when test="title != null">
and title like #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views > #{views}
</otherwise>
</choose>
</sql>
<select id="queryBlogChoose" parameterType="map" resultType="pojo.Blog">
select * from mybatistest.blog
<where>
<include refid="id-test"></include>
</where>
</select>
動態SQL
就是在拼接SQL語句,我們只要保證SQL的正確性,按照SQL的格式,去排列組合就可以了
我們可以先在Mysql中寫出完整的SQL,在對應的去修改稱為我們的動態SQL
緩存
1.簡介
查詢:連接數據庫,耗資源!
一次查詢的結果,給他暫存在一個可以直接取到的地方——內存:緩存
那么我們再次查詢的時候就可以不用走數據庫了
- 緩存【Cache】?
- 存在內存中的臨時數據
- 將用戶經常查詢的數據放在緩存中,用戶查詢的時候就不用從磁盤上查詢了,而從緩存中查詢,提高查詢效率
- 為什么使用緩存?
- 減少和數據庫的交互次數,減少系統開銷
- 什么樣的數據能使用緩存?
- 經常查詢並且不經常改變的數據
2.Mybatis緩存
Mybatis系統中默認頂一個兩級緩存:一級緩存和二級緩存
- 默認情況下,只有一級緩存開啟。這是sqlSession級別的,隨着Session開啟而開啟,關閉而關閉,也稱其為本地緩存
- 二級緩存是namespace級別的,需要手動開啟和配置
- Mybatis有一個配置緩存的接口Cache,可以定義二級緩存
注意事項:
- 映射語句文件中的所有 select 語句的結果將會被緩存。
- 映射語句文件中的所有 insert、update 和 delete 語句會刷新緩存。
- 緩存會使用最近最少使用算法(LRU, Least Recently Used)算法來清除不需要的緩存。
- 緩存不會定時進行刷新(也就是說,沒有刷新間隔)。
- 緩存會保存列表或對象(無論查詢方法返回哪種)的 1024 個引用。緩存會被視為讀/寫緩存,這意味着獲取到的對象並不是共享的,可以安全地被調用者修改,而不干擾其他調用者或線程所做的潛在修改。
3.一級緩存
一級緩存也叫本地緩存:
- 在域數據庫交互的同一個會話中,會將查過的數據放在緩存中
- 以后再查詢相同的數據時,直接從緩存中取數據
測試
- 開啟日志
- 測試兩次查詢同一條數據
@Test
public void cache(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
user user = mapper.getUserById(1);
System.out.println(user);
System.out.println("===============================");
user user1 = mapper.getUserById(1);
System.out.println(user1);
System.out.println(user==user1);
sqlSession.close();
}

從圖中可以看出,數據在一級緩存,只查詢一次,這兩者相同,為true
手動清理緩存
@Test
public void cache(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
user user = mapper.getUserById(1);
System.out.println(user);
sqlSession.clearCache(); //手動清理緩存
System.out.println("===============================");
user user1 = mapper.getUserById(1);
System.out.println(user1);
System.out.println(user==user1);
sqlSession.close();
}

從圖中可以看出,數據在一級緩存,手動清理緩存后,查詢了兩次,這兩者不同,為false
4.二級緩存
二級緩存是基於namespace的緩存,它的作用域比一級大
- 我們希望當會話關閉的時候,存儲在一級緩存的數據可以進入二級緩存
- 用戶進行第二次會話的時候,就可以直接從二級緩存拿數據
4.1 開啟緩存
在配置文件開啟二級緩存
<setting name="cacheEnabled" value="true"/>
在對應的mapper.xml
中選擇開啟二級緩存
<cache/>
也可以自定義cache
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
4.2測試
@Test
public void SecondCache(){
SqlSession sqlSession = mybatis_util.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
user user = mapper.getUserByID(1);
System.out.println(user);
sqlSession.close();
System.out.println("===============================");
SqlSession sqlSession1 = mybatis_util.getSqlSession();
UserDao mapper1 = sqlSession1.getMapper(UserDao.class);
user user1 = mapper1.getUserByID(1);
System.out.println(user1);
System.out.println(user==user1);
sqlSession.close();
}

從圖中可以看出,開啟二級緩存后,sqlSession關閉時,數據存入二級緩存,直接在二級緩存調出數據,只用查詢了一次 ,這兩者不同,為false
注意:可能會出現的錯誤:
Error serializing object. Cause:java.io.NotSerializableException: pojo.user
,這個錯誤只需要在實體類繼承Serializable
,即:class user implements Serializable
5.緩存原理
6.自定義緩存-encache
Ehcache是一種廣泛使用的開源Java分布式緩存。EhCache 是一個純Java的進程內緩存框架,具有快速、精干等特點,是Hibernate中默認的CacheProvider。
6.1 導入依賴
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.0</version>
</dependency>
6.2 導入配置文件
創建ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
6.3 開啟二級緩存
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
其實沒什么大的區別,想用可以用