MyBatis-Plus詳解(環(huán)境搭建、關聯(lián)操作)
MyBatis-Plus
MyBatis-Plus 是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發(fā)、提高效率而生。
官網 MyBatis-Plus
連接池: 傳統(tǒng)開發(fā)中,每一次請求都要建立一次數據庫連接。每一次數據庫連接,使用完后都得斷開。頻繁的數據庫連接操作勢必占用很多的系統(tǒng)資源,響應速度必定下降。另外,在高并發(fā)時,系統(tǒng)資源被毫無顧及的分配出去,如連接過多,也可能導致內存泄漏,服務器崩潰。
解決方案: 為數據庫連接建立一個“緩沖池”(連接池)。預先在緩沖池中放入一定數量的連接,當需要建立數據庫連接時,只需從“緩沖池”中取出一個,使用完畢再放回去。通過設定連接池最大連接數來防止系統(tǒng)無休止的數據庫連接。
工作流程: 當客戶端請求服務器,服務器需要使用連接對象操作數據庫的數據。這時,需要從連接池中申請一個連接對象。連接池會分配一個空閑連接給該客戶。如果連接池中沒有空閑連接,就看有沒有到達最大連接數。如果沒有到達最大連接數,就創(chuàng)建新連接分配給客戶。如果已經到達最大連接,那么,請求用戶會等待一段時間,在等待時間內,有連接對象被釋放,則分配給等待用戶。等待時間結束后,還沒有連接被釋放,則返回null。
Mybatis --- 環(huán)境搭建
1、導入相關依賴
<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)建實體類
//聲明該實體類映射的表名
@TableName("t_product")
public class ProductBean {
//表示該列為主鍵列,value表示該列映射的列名
//type = IdType.AUTO 表示該列的值使用自動增長列生成
@TableId(value = "pk_productId",type = IdType.AUTO)
private Integer id;
//指定當前屬性映射的列名
@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 #定義配置驅動類
username: root #mysql登錄用戶名
password: 123 #mysql登錄密碼
url: jdbc:mysql://localhost:12345/shopDB?characterEncoding=utf8&allowMultiQueries=true
type: com.alibaba.druid.pool.DruidDataSource #配置連接池
druid:
one:
max-active: 100 #最大連接數
min-idle: 20 #最小連接數
max-wait: 2000 #超時時間(ms)
?
?
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #配置日志
type-aliases-package: com.project.bean #實體類所在包,允許用實體類類名作為別名
mapper-locations: classpath:*/*Mapper.xml #鏈接 mapper文件4、創(chuàng)建業(yè)務接口
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、書寫業(yè)務接口實現類
@Service
@Transactional//該類所有方法支持事務
public class ProductServiceImpl implements IProductService {
@Autowired
private IProductMapper mapper;
@Override
public void add(ProductBean productBean) {
mapper.insert(productBean);//添加實體數據
}
?
@Override
public void del(Integer id) {
mapper.deleteById(id);//根據id刪除實體數據
}
?
@Override
public void update(Integer id, Integer price) {
ProductBean productBean = new ProductBean();
productBean.setId(id);
productBean.setPrice(price);
mapper.updateById(productBean);//按id修改實體屬性
}
?
@Override
public List<ProductBean> findAll() {
return mapper.selectList(null);//查詢所有
}
?
@Override
public ProductBean findById(Integer id) {
return mapper.selectById(id);//按id查詢實體對象
}
?
@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 模糊查詢
}
if (startDate != null){
qw.ge("p_creatDate",startDate);//ge 大于等于
}
if (endDate != null){
qw.le("p_createDate",endDate);//le 小于等于
}
return mapper.selectList(qw);//按條件查詢
}
}7、測試類
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Main.class)//啟動類類模板
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());
}
}分頁查詢
1、創(chuàng)建配置類,定義數據庫 SQL 語句的方言。Mybatis-plus會根據配置的方言,產生分頁的 SQL 語句
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(
new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
?}2、定義業(yè)務接口方法
/** * 動態(tài)條件分頁查詢 * @param pageNO 頁碼 * @param name 姓名 * @param startDate 生產起始日期 * @param endDate 生成結束日期 * @return 分頁對象 */ public IPage<ProductBean> findByItem(Integer pageNO, String name, LocalDate startDate,LocalDate endDate);
3、定義 mapper 接口
@Mapper
public interface IProductMapper extends BaseMapper<ProductBean> {
}4、書寫業(yè)務方法
@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、測試類
@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()//得到當前數據
+" "+ip.getTotal()//得到總記錄數
+" "+ip.getPages()//總頁數
+" "+ip.getCurrent()//得到頁碼
+" "+ip.getSize()//得到每頁記錄數
);
}
}Mybatis-plus 關聯(lián)操作
一對多:
1、創(chuàng)建實體類
/**
* 部門實體類
*/
@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)//標識該屬性沒有對應的列
private Integer emNum;
?
@TableField(exist = false)//標識該屬性沒有對應的列
private List<EmployeeBean> emList;
}
/**
* 員工實體類
*/
@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;
}注意:如果一個屬性沒有對應的列,必須加上@TableField(exist = false)。否則,maybatis-plus會認為數據庫表中有一個和該屬性同名列。
2、建立業(yè)務接口
/**
*部門業(yè)務接口
*/
public interface IDeptService {
/**
* 查詢所有部門,同時統(tǒng)計每個部門的人數
* @return 部門集合
*/
public List<DeptBean> findAll();
?
/**
* 級聯(lián)添加,添加部門,同時添加該部門的員工集合
* @param dept 部門對象
* @param emList 新員工集合
*/
public void add(DeptBean dept, List<EmployeeBean> emList);
?
/**
* 刪除部門,同時級聯(lián)刪除部門的員工
* @param id 部門ID
*/
public void delCasede(Integer id);
?
/**
* 刪除部門,同時將該部門員工外鍵設置為null
* @param id 部門ID
*/
public void delSerNull(Integer id);
?
/**
* 按id查詢部門,同時查詢該部門中所有的員工
* @param id 部門id
* @return 部門對象
*/
public DeptBean findById(Integer id);
}
/**
* 員工業(yè)務接口
*/
public interface IEmployeeService {
/**
* 添加員工
* @param employee 員工對象
*/
public void add(EmployeeBean employee);
?
/**
* 動態(tài)條件分頁查詢,同時查詢每個員工所在部門的名稱
* @param pageNO 頁碼
* @param deptName 部門名稱
* @param name 員工姓名
* @return 分頁對象
*/
public IPage<EmployeeBean> findByItem(Integer pageNO,
String deptName,String name);
?
/**
* 按id查詢員工,同時查詢員工的部門信息
* @param id 員工編號
* @return 員工對象33
*/
public EmployeeBean findById(Integer id);
}3、建立 Mapper 接口
/**
*部門 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);
?
}對于聯(lián)表查詢的結果集,動態(tài)條件查詢、循環(huán),都需要在 mapper 文件中完成。
4、書寫 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、書寫業(yè)務方法
/**
* 部門業(yè)務方法
*/
@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è)務方法
*/
@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)計查詢記錄數
QueryWrapper<StudentBean> qw = new QueryWrapper<>();
qw.eq("fk.classId",classId);
Integer num = studentMapper.selectCount(qw);到此這篇關于MyBatis-Plus詳解的文章就介紹到這了,更多相關MyBatis-Plus詳解內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java Spring-IOC容器與Bean管理之基于注解的方式案例詳解
這篇文章主要介紹了Java Spring-IOC容器與Bean管理之基于注解的方式案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-08-08
使用springboot打包成zip部署,并實現優(yōu)雅停機
這篇文章主要介紹了使用springboot打包成zip部署,并實現優(yōu)雅停機,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Java使用Spring JdbcTemplate向in語句中傳遞參數的教程詳解
這篇文章主要給大家介紹Java如何使用Spring JdbcTemplate向in語句中傳遞參數,文中有詳細的流程步驟和代碼示例,需要的朋友可以參考下2023-07-07
mybatis的好幫手之MybatisCodeHelperPro詳解
這篇文章主要介紹了mybatis的好幫手之MybatisCodeHelperPro詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09

