广告
返回顶部
首页 > 资讯 > 后端开发 > Python >MyBatis-Plus详解(环境搭建、关联操作)
  • 185
分享到

MyBatis-Plus详解(环境搭建、关联操作)

2024-04-02 19:04:59 185人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

目录mybatis-PlusMybatis --- 环境搭建1、导入相关依赖2、创建实体类3、在 resources 目录下,创建 application.yml 配置文件4、创建业

MyBatis-Plus

MyBatis-Plus 是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

官网 MyBatis-Plus

连接池: 传统开发中,每一次请求都要建立一次数据库连接。每一次数据库连接,使用完后都得断开。频繁的数据库连接操作势必占用很多的系统资源,响应速度必定下降。另外,在高并发时,系统资源被毫无顾及的分配出去,如连接过多,也可能导致内存泄漏,服务器崩溃。

解决方案: 为数据库连接建立一个“缓冲池”(连接池)。预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕再放回去。通过设定连接池最大连接数来防止系统无休止的数据库连接。

工作流程: 当客户端请求服务器,服务器需要使用连接对象操作数据库的数据。这时,需要从连接池中申请一个连接对象。连接池会分配一个空闲连接给该客户。如果连接池中没有空闲连接,就看有没有到达最大连接数。如果没有到达最大连接数,就创建新连接分配给客户。如果已经到达最大连接,那么,请求用户会等待一段时间,在等待时间内,有连接对象被释放,则分配给等待用户。等待时间结束后,还没有连接被释放,则返回null。

Mybatis --- 环境搭建

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、创建实体类

//声明该实体类映射的表名
@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 目录下,创建 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:*
public IPage<ProductBean> findByItem(Integer pageNO, 
String name, LocalDate startDate,LocalDate endDate);

3、定义 mapper 接口

@Mapper
public interface IProductMapper extends BaseMapper<ProductBean> {
}

4、书写业务方法

@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 关联操作

一对多:

1、创建实体类


@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、建立业务接口


public interface IDeptService {
    
    public List<DeptBean> findAll();
​
    
    public void add(DeptBean dept, List<EmployeeBean> emList);
​
    
    public void delCasede(Integer id);
​
    
    public void delSerNull(Integer id);
​
    
    public DeptBean findById(Integer id);
}




public interface IEmployeeService {
    
    public void add(EmployeeBean employee);
​
    
    public IPage<EmployeeBean> findByItem(Integer pageNO,
String deptName,String name);
​
    
    public EmployeeBean findById(Integer id);
}

3、建立 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
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);
​
}

对于联表查询的结果集,动态条件查询、循环,都需要在 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、书写业务方法


@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;
    }
}

@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;
    }
}

统计查询记录数

QueryWrapper<StudentBean> qw = new QueryWrapper<>();
qw.eq("fk.classId",classId);
Integer num = studentMapper.selectCount(qw);

到此这篇关于MyBatis-Plus详解的文章就介绍到这了,更多相关MyBatis-Plus详解内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: MyBatis-Plus详解(环境搭建、关联操作)

本文链接: https://www.lsjlt.com/news/166959.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作