MyBatis-Plus詳解(環(huán)境搭建、關(guān)聯(lián)操作)
MyBatis-Plus
MyBatis-Plus 是一個(gè) MyBatis 的增強(qiáng)工具,在 MyBatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開(kāi)發(fā)、提高效率而生。
官網(wǎng) MyBatis-Plus
連接池: 傳統(tǒng)開(kāi)發(fā)中,每一次請(qǐng)求都要建立一次數(shù)據(jù)庫(kù)連接。每一次數(shù)據(jù)庫(kù)連接,使用完后都得斷開(kāi)。頻繁的數(shù)據(jù)庫(kù)連接操作勢(shì)必占用很多的系統(tǒng)資源,響應(yīng)速度必定下降。另外,在高并發(fā)時(shí),系統(tǒng)資源被毫無(wú)顧及的分配出去,如連接過(guò)多,也可能導(dǎo)致內(nèi)存泄漏,服務(wù)器崩潰。
解決方案: 為數(shù)據(jù)庫(kù)連接建立一個(gè)“緩沖池”(連接池)。預(yù)先在緩沖池中放入一定數(shù)量的連接,當(dāng)需要建立數(shù)據(jù)庫(kù)連接時(shí),只需從“緩沖池”中取出一個(gè),使用完畢再放回去。通過(guò)設(shè)定連接池最大連接數(shù)來(lái)防止系統(tǒng)無(wú)休止的數(shù)據(jù)庫(kù)連接。
工作流程: 當(dāng)客戶(hù)端請(qǐng)求服務(wù)器,服務(wù)器需要使用連接對(duì)象操作數(shù)據(jù)庫(kù)的數(shù)據(jù)。這時(shí),需要從連接池中申請(qǐng)一個(gè)連接對(duì)象。連接池會(huì)分配一個(gè)空閑連接給該客戶(hù)。如果連接池中沒(méi)有空閑連接,就看有沒(méi)有到達(dá)最大連接數(shù)。如果沒(méi)有到達(dá)最大連接數(shù),就創(chuàng)建新連接分配給客戶(hù)。如果已經(jīng)到達(dá)最大連接,那么,請(qǐng)求用戶(hù)會(huì)等待一段時(shí)間,在等待時(shí)間內(nèi),有連接對(duì)象被釋放,則分配給等待用戶(hù)。等待時(shí)間結(jié)束后,還沒(méi)有連接被釋放,則返回null。
Mybatis --- 環(huán)境搭建
1、導(dǎo)入相關(guān)依賴(lài)
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.9</version>
</dependency>
</dependencies>2、創(chuàng)建實(shí)體類(lèi)
//聲明該實(shí)體類(lèi)映射的表名
@TableName("t_product")
public class ProductBean {
//表示該列為主鍵列,value表示該列映射的列名
//type = IdType.AUTO 表示該列的值使用自動(dòng)增長(zhǎng)列生成
@TableId(value = "pk_productId",type = IdType.AUTO)
private Integer id;
//指定當(dāng)前屬性映射的列名
@TableField("p_name")
private String name;
?
@TableField("p_createDate")
private LocalDate createDate;
?
@TableField("p_price")
private Integer price;
}3、在 resources 目錄下,創(chuàng)建 application.yml 配置文件
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver #定義配置驅(qū)動(dòng)類(lèi)
username: root #mysql登錄用戶(hù)名
password: 123 #mysql登錄密碼
url: jdbc:mysql://localhost:12345/shopDB?characterEncoding=utf8&allowMultiQueries=true
type: com.alibaba.druid.pool.DruidDataSource #配置連接池
druid:
one:
max-active: 100 #最大連接數(shù)
min-idle: 20 #最小連接數(shù)
max-wait: 2000 #超時(shí)時(shí)間(ms)
?
?
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #配置日志
type-aliases-package: com.project.bean #實(shí)體類(lèi)所在包,允許用實(shí)體類(lèi)類(lèi)名作為別名
mapper-locations: classpath:*/*Mapper.xml #鏈接 mapper文件4、創(chuàng)建業(yè)務(wù)接口
public interface IProductService {
?
public void add(ProductBean productBean);
public void del(Integer id);
public void update(Integer id,Integer price);
public List<ProductBean> findAll();
public ProductBean findById(Integer id);
public List<ProductBean> findByItem(String name,
LocalDate startDate,LocalDate endDate);
}5、創(chuàng)建 mapper 接口
@Mapper
public interface IProductMapper extends BaseMapper<ProductBean> {
}6、書(shū)寫(xiě)業(yè)務(wù)接口實(shí)現(xiàn)類(lèi)
@Service
@Transactional//該類(lèi)所有方法支持事務(wù)
public class ProductServiceImpl implements IProductService {
@Autowired
private IProductMapper mapper;
@Override
public void add(ProductBean productBean) {
mapper.insert(productBean);//添加實(shí)體數(shù)據(jù)
}
?
@Override
public void del(Integer id) {
mapper.deleteById(id);//根據(jù)id刪除實(shí)體數(shù)據(jù)
}
?
@Override
public void update(Integer id, Integer price) {
ProductBean productBean = new ProductBean();
productBean.setId(id);
productBean.setPrice(price);
mapper.updateById(productBean);//按id修改實(shí)體屬性
}
?
@Override
public List<ProductBean> findAll() {
return mapper.selectList(null);//查詢(xún)所有
}
?
@Override
public ProductBean findById(Integer id) {
return mapper.selectById(id);//按id查詢(xún)實(shí)體對(duì)象
}
?
@Override
public List<ProductBean> findByItem(String name,
LocalDate startDate, LocalDate endDate) {
QueryWrapper<ProductBean> qw = new QueryWrapper<>();//條件集合
if (name != null && name.length() != 0){
qw.like("p_name",name);//like 模糊查詢(xún)
}
if (startDate != null){
qw.ge("p_creatDate",startDate);//ge 大于等于
}
if (endDate != null){
qw.le("p_createDate",endDate);//le 小于等于
}
return mapper.selectList(qw);//按條件查詢(xún)
}
}7、測(cè)試類(lèi)
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Main.class)//啟動(dòng)類(lèi)類(lèi)模板
public class ProductTest {
@Autowired
private IProductService service;
?
@Test
public void test(){
// service.add(new ProductBean("999感冒靈",
LocalDate.parse("2022-06-06"),18));
System.out.println(service.findAll());
}
}分頁(yè)查詢(xún)
1、創(chuàng)建配置類(lèi),定義數(shù)據(jù)庫(kù) SQL 語(yǔ)句的方言。Mybatis-plus會(huì)根據(jù)配置的方言,產(chǎn)生分頁(yè)的 SQL 語(yǔ)句
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(
new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
?}2、定義業(yè)務(wù)接口方法
/** * 動(dòng)態(tài)條件分頁(yè)查詢(xún) * @param pageNO 頁(yè)碼 * @param name 姓名 * @param startDate 生產(chǎn)起始日期 * @param endDate 生成結(jié)束日期 * @return 分頁(yè)對(duì)象 */ public IPage<ProductBean> findByItem(Integer pageNO, String name, LocalDate startDate,LocalDate endDate);
3、定義 mapper 接口
@Mapper
public interface IProductMapper extends BaseMapper<ProductBean> {
}4、書(shū)寫(xiě)業(yè)務(wù)方法
@Override
public IPage<ProductBean> findByItem(Integer pageNO,
String name, LocalDate startDate, LocalDate endDate) {
QueryWrapper<ProductBean> qw = new QueryWrapper<>();
if (name != null && name.length() != 0){
qw.like("p_name",name);
}
if (startDate != null){
qw.ge("p_createDate",startDate);
}
if (endDate != null){
qw.le("p_createDate",endDate);
}
return mapper.selectPage(new Page(pageNO,3),qw);
}5、測(cè)試類(lèi)
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PlusMain.class)
public class Test {
@Autowired
private IProductService service;
@org.junit.Test
public void test(){
// System.out.println(service.findAll());
IPage ip = service.findByItem(1,"",null,null);
System.out.println(ip.getRecords()//得到當(dāng)前數(shù)據(jù)
+" "+ip.getTotal()//得到總記錄數(shù)
+" "+ip.getPages()//總頁(yè)數(shù)
+" "+ip.getCurrent()//得到頁(yè)碼
+" "+ip.getSize()//得到每頁(yè)記錄數(shù)
);
}
}Mybatis-plus 關(guān)聯(lián)操作
一對(duì)多:
1、創(chuàng)建實(shí)體類(lèi)
/**
* 部門(mén)實(shí)體類(lèi)
*/
@TableName("t_dept")
public class DeptBean {
@TableId(value = "pk_deptId",type = IdType.AUTO)
private Integer id;
?
@TableField("d_name")
private String name;
?
@TableField(exist = false)//標(biāo)識(shí)該屬性沒(méi)有對(duì)應(yīng)的列
private Integer emNum;
?
@TableField(exist = false)//標(biāo)識(shí)該屬性沒(méi)有對(duì)應(yīng)的列
private List<EmployeeBean> emList;
}
/**
* 員工實(shí)體類(lèi)
*/
@TableName("t_employee")
public class EmployeeBean {
@TableId(value = "pk_emId",type = IdType.AUTO)
private Integer id;
@TableField("e_name")
private String name;
@TableField("e_job")
private String job;
@TableField("e_birthday")
private LocalDate birthday;
@TableField("fk_deptId")
private Integer deptId;
@TableField(exist = false)
private DeptBean dept;
}注意:如果一個(gè)屬性沒(méi)有對(duì)應(yīng)的列,必須加上@TableField(exist = false)。否則,maybatis-plus會(huì)認(rèn)為數(shù)據(jù)庫(kù)表中有一個(gè)和該屬性同名列。
2、建立業(yè)務(wù)接口
/**
*部門(mén)業(yè)務(wù)接口
*/
public interface IDeptService {
/**
* 查詢(xún)所有部門(mén),同時(shí)統(tǒng)計(jì)每個(gè)部門(mén)的人數(shù)
* @return 部門(mén)集合
*/
public List<DeptBean> findAll();
?
/**
* 級(jí)聯(lián)添加,添加部門(mén),同時(shí)添加該部門(mén)的員工集合
* @param dept 部門(mén)對(duì)象
* @param emList 新員工集合
*/
public void add(DeptBean dept, List<EmployeeBean> emList);
?
/**
* 刪除部門(mén),同時(shí)級(jí)聯(lián)刪除部門(mén)的員工
* @param id 部門(mén)ID
*/
public void delCasede(Integer id);
?
/**
* 刪除部門(mén),同時(shí)將該部門(mén)員工外鍵設(shè)置為null
* @param id 部門(mén)ID
*/
public void delSerNull(Integer id);
?
/**
* 按id查詢(xún)部門(mén),同時(shí)查詢(xún)?cè)摬块T(mén)中所有的員工
* @param id 部門(mén)id
* @return 部門(mén)對(duì)象
*/
public DeptBean findById(Integer id);
}
/**
* 員工業(yè)務(wù)接口
*/
public interface IEmployeeService {
/**
* 添加員工
* @param employee 員工對(duì)象
*/
public void add(EmployeeBean employee);
?
/**
* 動(dòng)態(tài)條件分頁(yè)查詢(xún),同時(shí)查詢(xún)每個(gè)員工所在部門(mén)的名稱(chēng)
* @param pageNO 頁(yè)碼
* @param deptName 部門(mén)名稱(chēng)
* @param name 員工姓名
* @return 分頁(yè)對(duì)象
*/
public IPage<EmployeeBean> findByItem(Integer pageNO,
String deptName,String name);
?
/**
* 按id查詢(xún)員工,同時(shí)查詢(xún)員工的部門(mén)信息
* @param id 員工編號(hào)
* @return 員工對(duì)象33
*/
public EmployeeBean findById(Integer id);
}3、建立 Mapper 接口
/**
*部門(mén) mapper 接口
*/
@Mapper
public interface IDeptMapper extends BaseMapper<DeptBean> {
@Select("SELECT d.*,COUNT(e.`pk_emId`) emNum FROM t_dept d LEFT JOIN
t_employee e ON d.`pk_deptId`=e.`fk_deptId`\n" +
"GROUP BY d.`pk_deptId`")
@ResultMap("deptMap")
public List<DeptBean> findAll();
?
@Delete("delete from t_employee where fk_deptId=#{id};" +
"delete from t_dept where pk_deptId=#{id};")
public void delCasede(Integer id);
?
@Delete("update t_employee set fk_deptId=null where fk_deptId=#{id};" +
"delete from t_dept where pk_deptId=#{id};")
public void delSetNull(Integer id);
}
/**
*員工 mapper 接口
*/
@Mapper
public interface IEmployeeMapper extends BaseMapper<EmployeeBean> {
?
public void addMore(@Param("deptId") Integer deptId,
@Param("emList") List<EmployeeBean> emList);
?
public IPage<EmployeeBean> findByItem(Page pageNO,
@Param("deptName") String deptName,@Param("name") String name);
?
}對(duì)于聯(lián)表查詢(xún)的結(jié)果集,動(dòng)態(tài)條件查詢(xún)、循環(huán),都需要在 mapper 文件中完成。
4、書(shū)寫(xiě) mapper 文件
IDeptMapper:
<mapper namespace="com.project.mapper.IDeptMapper">
<resultMap id="deptMap" type="DeptBean">
<id property="id" column="pk_deptId"></id>
<result property="name" column="d_name"></result>
<result property="emNum" column="emNum"></result>
</resultMap>
</mapper>IEmployeeMapper:
<mapper namespace="com.project.mapper.IEmployeeMapper">
<insert id="addMore">
insert into t_employee (e_name,e_job,e_birthday,fk_deptId)
values
<foreach collection="emList" item="em" separator=",">
(#{em.name},#{em.job},#{em.birthday},#{deptId})
</foreach>
</insert>
?
<resultMap id="emMap" type="EmployeeBean">
<id column="pk_emId" property="id"></id>
<result column="e_name" property="name"></result>
<result column="e_job" property="job"></result>
<result column="e_birthday" property="birthday"></result>
<result column="d_name" property="dept.name"></result>
</resultMap>
?
<select id="findByItem" resultMap="emMap">
select e.*,d.d_name from t_dept d,t_employee e where
d.pk_deptId=e.fk_deptId
<if test="deptName != null and deptName != '' ">
and d_name like "%"#{deptName}"%"
</if>
<if test="name != null and name != '' ">
and e_name like "%"#{name}"%"
</if>
</select>
</mapper>5、書(shū)寫(xiě)業(yè)務(wù)方法
/**
* 部門(mén)業(yè)務(wù)方法
*/
@Service
@Transactional
public class DeptServiceImpl implements IDeptService {
?
@Autowired
private IDeptMapper deptMapper;
@Autowired
private IEmployeeMapper employeeMapper;
?
@Override
public List<DeptBean> findAll() {
return deptMapper.findAll();
}
?
@Override
public void add(DeptBean dept, List<EmployeeBean> emList) {
deptMapper.insert(dept);
employeeMapper.addMore(dept.getId(),emList);
}
?
@Override
public void delCasede(Integer id) {
deptMapper.delCasede(id);
}
?
@Override
public void delSerNull(Integer id) {
deptMapper.delSetNull(id);
}
?
@Override
public DeptBean findById(Integer id) {
DeptBean dept = deptMapper.selectById(id);
QueryWrapper<EmployeeBean> qw = new QueryWrapper<>();
qw.eq("fk_deptId",id);
dept.setEmList(employeeMapper.selectList(qw));
return dept;
}
}
/**
* 員工業(yè)務(wù)方法
*/
@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {
@Autowired
IEmployeeMapper employeeMapper;
@Autowired
IDeptMapper deptMapper;
@Override
public void add(EmployeeBean employee) {
employeeMapper.insert(employee);
}
?
@Override
public IPage<EmployeeBean> findByItem(Integer pageNO,
String deptName, String name) {
return employeeMapper.findByItem(new Page(pageNO,3),deptName,name);
}
?
@Override
public EmployeeBean findById(Integer id) {
EmployeeBean em = employeeMapper.selectById(id);
em.setDept(deptMapper.selectById(em.getDeptId()));
·· return em;
}
}統(tǒng)計(jì)查詢(xún)記錄數(shù)
QueryWrapper<StudentBean> qw = new QueryWrapper<>();
qw.eq("fk.classId",classId);
Integer num = studentMapper.selectCount(qw);到此這篇關(guān)于MyBatis-Plus詳解的文章就介紹到這了,更多相關(guān)MyBatis-Plus詳解內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- MybatisPlus實(shí)現(xiàn)對(duì)象嵌套關(guān)聯(lián)查詢(xún)一對(duì)多List集合查詢(xún)
- mybatis主從表關(guān)聯(lián)查詢(xún),返回對(duì)象帶有集合屬性解析
- mybatis多表查詢(xún)的實(shí)現(xiàn)(xml方式)
- springboot整合mybatis實(shí)現(xiàn)多表查詢(xún)的實(shí)戰(zhàn)記錄
- MyBatis如何實(shí)現(xiàn)多表查詢(xún)(多對(duì)一、一對(duì)多)
- MybatisPlus自定義Sql實(shí)現(xiàn)多表查詢(xún)的示例
- 結(jié)合mybatis-plus實(shí)現(xiàn)簡(jiǎn)單不需要寫(xiě)sql的多表查詢(xún)
- MyBatis中的關(guān)聯(lián)關(guān)系配置與多表查詢(xún)的操作代碼
相關(guān)文章
Java Spring-IOC容器與Bean管理之基于注解的方式案例詳解
這篇文章主要介紹了Java Spring-IOC容器與Bean管理之基于注解的方式案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
Java8函數(shù)式接口Predicate用法示例詳解
這篇文章主要為大家介紹了Java8函數(shù)式接口Predicate用法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
springboot項(xiàng)目不輸出nohup.out日志的解決
這篇文章主要介紹了springboot項(xiàng)目不輸出nohup.out日志的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
springboot-curd基于mybatis項(xiàng)目搭建
這篇文章主要介紹了springboot-curd基于mybatis項(xiàng)目搭建,圍繞相關(guān)資料展開(kāi)詳細(xì)內(nèi)容,希望對(duì)正在學(xué)習(xí)的你有所幫助,需要的小伙伴也可以參考一下2022-01-01
使用springboot打包成zip部署,并實(shí)現(xiàn)優(yōu)雅停機(jī)
這篇文章主要介紹了使用springboot打包成zip部署,并實(shí)現(xiàn)優(yōu)雅停機(jī),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
詳解SpringBoot時(shí)間參數(shù)處理完整解決方案
這篇文章主要介紹了詳解SpringBoot時(shí)間參數(shù)處理完整解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
Java使用Spring JdbcTemplate向in語(yǔ)句中傳遞參數(shù)的教程詳解
這篇文章主要給大家介紹Java如何使用Spring JdbcTemplate向in語(yǔ)句中傳遞參數(shù),文中有詳細(xì)的流程步驟和代碼示例,需要的朋友可以參考下2023-07-07
mybatis的好幫手之MybatisCodeHelperPro詳解
這篇文章主要介紹了mybatis的好幫手之MybatisCodeHelperPro詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09

