1.認識Mybatis
??MyBatis和JPA一樣,也是一款優秀的持久層框架,它支持定制化SQL、存盤程序,以及高級映射,它可以使用簡單的XML或注解來配置和映射原生資訊,將介面和Java的POJOs ( Plain Old Java Objects,普通的Java物件)映射成資料庫中的記錄,
??MyBatis 3提供的注解可以取代XML例如,使用注解@Select直接撰寫SQL完成資料查詢; 使用高級注解@SelectProvider還可以撰寫動態SQL,以應對復雜的業務需求,
2.Mybatis詳細介紹
2.1 CRUD注解
??増加、洗掉、修改和查詢是主要的業務操作,必須掌握這些基礎注解的使用方法,MyBatis提供的操作資料的基礎注解有以下4個,
- @Select:用于構建查詢陳述句,
- @Insert:用于構建添加陳述句,
- @Update:用于構建修改陳述句,
- @Delete:用于構建洗掉陳述句,
??下面來看看它們具體如何使用,見以下代碼:
package com.itheima.mapper;
import com.itheima.domain.User;
import org.apache.ibatis.annotations.*;
import org.springframework.data.domain.Page;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
User queryById(@Param("id")int id);
@Select("select * from user")
List<User> queryAll();
@Insert({"insert into user(name,age) values(#{name},#{age})"})
int add(User user);
@Delete("delete from user where id = #{id}")
int delete(int id);
@Update("update user set name = #{name},age = #{age} where id = #{id}")
int updateById(User user);
@Select("select * from user")
Page<User> getUserList();
}
??從上述代碼可以看岀:首先要用@Mapper注解來標注類,把UserMapper這個DAO交給 Spring管理,這樣Spring會自動生成一個實作類,不用再寫UserMapper的映射檔案了,最后使用基礎的CRUD注解來添加要實作的功能,
2.2 映射注解
MyBatis的映射注解用于建立物體和關系的映射,它有以下3個注解,
- @Results:用于填寫結果集的多個欄位的映射關系,
- @Result:用于填寫結果集的單個欄位的映射關系,
- @ResultMap:根據 ID 關聯 XML 里面的<resultMap>
??可以在查詢SQL的基礎上,指定回傳的結果集的映射關系,其中,property表示物體物件的屬性名,column表示對應的資料庫欄位名,使用方法見以下代碼:
@Results({
@Result(property = "username",column = "USERNAME"),
@Result(property = "password",column = "PASSWORD")
})
@Select("select * from user ")
List<User> list();
2.3高級注解
??1.高級注解
??MyBatis 3.x版本主要提供了以下4個CRUD的高級注解,
- @SelectProvider:用于構建動態查詢SQL,
- @lnsertProvider:用于構建動態添加SQL,
- @UpdateProvider:用于構建動態更新SQL,
- @DeleteProvider:用于構建動態洗掉SQL,
??高級注解主要用于撰寫動態SQL,這里以@SelectProvider為例,它主要包含兩個注解屬性, 其中,type表示工具類,method表示工具類的某個方法(用于回傳具體的SQL ),以下代碼可以構建動態SQL,實作查詢功能:
package com.itheima.mapper;
import com.itheima.domain.User;
import com.itheima.util.UserSql;
import org.apache.ibatis.annotations.*;
import org.springframework.data.domain.Page;
import java.util.List;
@Mapper
public interface UserMapper {
@SelectProvider(type = UserSql.class,method = "listAll")
List<User> listAllUsers();
}
package com.itheima.util;
public class UserSql {
public String listAll(){
return "SELECT * FROM user";
}
}
??2. MyBatis3注解的用法舉例
??(1)如果要查詢所有的值,則基礎CRUD的代碼是:
@Select("select * from user")
List<User> queryAll();
??也可以用映射注解來一一映射,見以下代碼:
@Select("select * from user")
@Results({
@Result(property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "age",column = "age")
})
List<User> listAll();
??(2)用多個引數進行查詢,
??如果要用多個引數逬行查詢,則必須加上注解@Param,否則無法使用EL運算式獲取引數.
@Select("select * from user where name like #{name} and age like #{age}")
User getUserByNameAndAge(@Param("name") String name, @Param("age") int age);
??還可以根據官方提供的API來撰寫動態SQL
public static String getUser(@Param("name") String name, @Param("age") int age){
return new SQL(){{
SELECT("*");
FROM("user");
if (name != null && age != 0){
WHERE("name like #{name} and age like #{age}");
}else {
WHERE("1=2");
}
}}.toString();
}
??3.實體:用MyBatis實作資料的增加、洗掉、修改、查詢和分頁
??(1)創建物體類
@Data
public class User{
private int id;
private String name;
private int age;
}
??(2)實作物體和資料表的映射關系
??實作物體和資料表的映射關系可以在Mapper類上添加注解@Mapper,見以下代碼,建議以 后直接在入口類加@MapperScan(" com.itheima.mapper"),如果対每個 Mapper 都加注解則很麻煩
package com.itheima.mapper;
import com.itheima.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
User queryById(@Param("id")int id);
@Select("select * from user")
List<User> queryAll();
@Insert({"insert into user(name,age) values(#{name},#{age})"})
int add(User user);
@Delete("delete from user where id = #{id}")
int delete(int id);
@Update("update user set name = #{name},age = #{age} where id = #{id}")
int updateById(User user);
}
3.配置分頁功能
??(1)增加分頁依賴
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.0.7.RELEASE</version>
</dependency>
??(2)創建分頁配置類
package com.itheima.config;
import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class PageHelperConfig {
@Bean
public PageHelper pageHelper(){
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("offsetAsPageNum","true");
properties.setProperty("rowBoundsWithCount","true");
properties.setProperty("reasonable","true");
pageHelper.setProperties(properties);
return pageHelper;
}
}
代碼解釋如下,
- @Configuration: 表示PageHelperConfig這個類是用來做配置的,
- @Bean:表示啟動PageHelper攔截器,
- offsetAsPageNum: 當設定為 true 時,會將 RowBounds 第 1 個引數 offset 當成 pageNum (頁碼)使用,
- rowBoundsWithCount:當設定為true時,使用RowBounds分頁會進行count查詢,
- reasonable :在啟用合理化時,如果pageNum<1 ,則會查詢第一頁;如果 pageNum>pages,則會查詢最后一頁,
??(3)實作分頁控制器
??1.實作分頁控制器:
package com.itheima.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Controller
public class UserListController {
@Autowired
UserMapper userMapper;
@RequestMapping("/pagelist")
public String listCategory(Model model, @RequestParam(value = "https://www.cnblogs.com/liwenruo/archive/2022/07/23/start",defaultValue = "https://www.cnblogs.com/liwenruo/archive/2022/07/23/1") int start,
@RequestParam(value = "https://www.cnblogs.com/liwenruo/archive/2022/07/23/size",defaultValue = "https://www.cnblogs.com/liwenruo/archive/2022/07/23/20") int size) {
PageHelper.startPage(start, size,"id desc");
List<User> users = userMapper.queryAll();
PageInfo<User> page = new PageInfo<>(users);
model.addAttribute("page", page);
return "list";
}
}
代碼解釋如下,
- start:在引數里接收當前是第幾頁,
- size:每頁顯示多少條資料,默認值分別是0和20
- startPage(start,size,"id desc"):根據 start、size 進行分頁,并且設定 id 倒排序,
- List<User>:回傳當前分頁的集合,
- Pagelnfo<User>:根據回傳的集合創建Pagelnfo対象,
- addAttribute("page", page):把 page ( Pagelnfo 物件)傳遞給視圖,以供后續顯示,
??2.創建分頁視圖:
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/tyemeleaf-extras-springsecurity5">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:each="u:${page.list}">
<span scope = "row" th:text="${u.id}">id</span>
<span th:text="${u.name}">name</span>
</div>
<div>
<a th:href="https://www.cnblogs.com/liwenruo/archive/2022/07/23/@{pagelist?start=1}">[首頁]</a>
<a th:if="${not page.isFirstPage}" th:href="https://www.cnblogs.com/liwenruo/archive/2022/07/23/@{/pagelist(start=${page.pageNum-1})}">[上頁]</a>
<a th:if="${not page.isLastPage}" th:href="https://www.cnblogs.com/liwenruo/archive/2022/07/23/@{/pagelist(start=${page.pageNum+1})}">[下頁]</a>
<a th:href="https://www.cnblogs.com/liwenruo/archive/2022/07/23/@{/pagelist(start=${page.pages})}">[末頁]</a>
<div>
當前頁/總頁數:<a th:text="${page.pageNum}" th:href="https://www.cnblogs.com/liwenruo/archive/2022/07/23/@{pagelist(start=${page.pageNum})}"></a>
/<a th:text="${page.pages}" th:href="https://www.cnblogs.com/liwenruo/archive/2022/07/23/@{/pagelist(start=${page.pages})}"></a>
</div>
</div>
</body>
</html>
3.比較JPA與Mybatis
1.關注度
JPA在全球范圍內的用戶數最多,而MyBatis是國內互聯網公司的主流選擇
2.Hibernate 的優勢
- DAO層開發比MyBatis簡單,MyBatis需要維護SQL和結果映射,
- 對物件的維護和快取要比MyBatis好,對増加、洗掉、修改和查詢物件的維護更方便,
- 資料庫移植性很好,MyBatis的資料庫移植性不好,不同的資料庫需要寫不同的SQL陳述句,
- 有更好的二級快取機制,可以使用第三方快取,MyBatis本身提供的快取機制不佳,
3.MyBatis的優勢
- 可以進行更為細致的SQL優化,可以減少查詢欄位(大部分人這么認為,但是實際上 Hibernate —樣可以實作),
- 容易掌握,Hibernate門檻較高(大部分人都這么認為)
4.簡單總結
- MyBatis:小巧、方便、高效、簡單、直接、半自動化,
- Hibernate:強大、方便、高效、復雜、間接、全自動化,
它們各自的缺點都可以依據各目更深入的技術方案來解決,所以,筆者的建議是:
- 如果沒有SQL語言的基礎,則建議使用JPA,
- 如果有SQL語言基礎,則建議使用MyBatis,因為國內使用MyBatis的人比使用JPA的人多很多,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/500105.html
標籤:其他
