Mybatis框架(1)


链接: 下一篇Mybatis框架(2)

Mybatis框架(1)

Mybatis框架的主要作用

Mybatis框架主要实现了简化持久层编程的问题。

持久层:实现数据持久化的一系列组件。

数据持久化:通常,在开发领域中,讨论的数据大多是在内存中的,而内存默认特指内存条(RAM:Random Access Memory),RAM的特性包含“一旦断电,数据将全部丢失”,且“正在执行的程序和数据都是在内存中的”,由程序处理的数据最终应该永久的保存下来,则不能将这些数据一直只存储在内存中,通常,会将数据存储到可以永久保存数据的存储介质中,典型的永久存储数据的存储介质有:硬盘、U盘、光盘等,所以,数据持久化就是将内存中的数据存储到硬盘等介质中,而硬盘中的数据是以文件的形式存在的,所以,通常可以将数据存储到文本文件中、XML文件、数据库中,这些存储方案中,只有数据库是便于实现增、删、改、查这4种操作的,所以,一般“数据持久化”默认指的就是将数据存储到数据库中。

在Java语言中,实现数据库编程需要先建立与数据库的连接,然后准备SQL语句,然后执行,然后获取执行结果并处理结果,最后,关闭或归还数据库连接,这是一套非常固定的流程,无论对哪个数据表执行哪种操作,其流程大致是固定的,所以,就产生了一些框架,用于简化这部分的编程。

在使用Mybatis时,只需要关注2点:

  • 在接口中定义抽象方法
  • 配置抽象方法映射的SQL语句

使用Mybatis的前期准备

在Spring Boot项目中,当需要使用Mybatis时,需要添加相关的依赖:

<!-- MySQL依赖项,仅运行时需要 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!-- Mybatis整合Spring Boot的框架 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

当添加以上依赖项后,如果启动项目,会提示以下错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

因为Spring Boot启动时,如果检测到当前已经添加数据库编程的依赖项,会自动读取连接数据库的配置信息,由于目前尚未配置这些信息,所以,启动会报错!

所以,需要在application.properties中添加配置:

# 连接数据库的参数
spring.datasource.url=jdbc:mysql://localhost:3306/mall_pms?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root

由于Spring Boot在启动项目时只会读取以上配置并应用,并不会实际的连接数据库,所以,即使以上配置值是错误的,启动项目时并不会报告错误!

可以在src/test/java的根包下的测试类中进行测试连接:

@SpringBootTest
class CsmallProductApplicationTests {

    @Test
    void contextLoads() {
    }

    @Autowired
    DataSource dataSource;

    @Test
    void testConnection() throws Exception {
        dataSource.getConnection();
    }

}

当配置的URL错误(含主机名错误、端口号错误),或MySQL未启动时,将出现以下错误:

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

如果数据库名称错误,或无此数据库,将出现以下错误:

java.sql.SQLSyntaxErrorException: Unknown database 'mall_pmsxzxxxxx'

如果用户或密码错误,将出现以下错误:

java.sql.SQLException: Access denied for user 'rootx'@'localhost' (using password: YES)
java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: NO)

使用Mybatis插入数据

Mybatis要求抽象方法必须存在于接口中(因为其实现原理是基于接口的代理模式的),所以,在项目的根包下创建mapper.AlbumMapper接口。

提示:可以在接口上添加@Repository注解,避免在自动装配时IntelliJ IDEA误判而提示错误。

关于接口中的抽象方法:

  • 返回值类型:如果需要执行的SQL是增、删、改类型的,使用int作为返回值类型,表示“受影响的行数”,不建议使用void
  • 方法名称 :自定义,不要使用重载
    • 获取单个对象的方法用get做前缀
    • 获取多个对象的方法用list做前缀
    • 获取统计值的方法用count做前缀
    • 插入的方法用save/insert做前缀
    • 删除的方法用remove/delete做前缀
    • 修改的方法用update做前缀
  • 参数列表:如果需要执行的SQL语句有多个参数,应该将这些参数封装到自定义的数据类型中,并使用自定义的数据类型作为抽象方法的参数

则,插入相册时需要执行的SQL语句大致是:

insert into pms_album (name, description, sort, gmt_create, gmt_modified) values (?, ?, ?, ?, ?);

则抽象方法为:

int insert(Album album);

首次使用时,需要让Mybatis知道哪些接口是Mapper接口,可以(二选一):

  • 在每个接口上添加@Mapper注解
  • 配置类上添加@MapperScan并指定Mapper接口所在的包
    • 在根包下的任何类,添加了@Configuration注解,即是配置类
    • 可以在根包下创建config.MybatisConfiguration类,同时添加@Configuration@MapperScan("cn.tedu.csmall.product.mapper")即可

另外,在使用Mybatis时,还需要为每个抽象方法配置其映射的SQL语句,可以使用@Insert等注解来配置SQL语句,但不推荐,因为:

  • 不便于配置较长的SQL语句
  • 不便于做一些复杂的配置,特别是查询时
  • 不便于实现与DBA(Database Administrator)分工合作

建议的做法是使用XML文件来配置SQL语句,可以从 http://doc.canglaoshi.org/config/Mapper.xml.zip 下载得到所需的文件,然后,在项目的src/main/resources下创建mapper文件夹,将得下载、解压得到的XML文件复制到此文件夹中。

关于配置SQL的XML文件:

  • 根节点必须是<mapper>
  • <mapper>上必须配置namespace属性,取值为对应的接口的全限定名
  • <mapper>的子级,根据需要执行的SQL语句,选择使用<insert><delete><update><select>中的某个节点,准备配置SQL语句,这些节点必须配置id属性,取值为抽象方法的名称(不包括括号和参数列表),并在这些节点内部配置SQL语句

提示:在本项目中,当插入数据时,不需要关注gmtCreategmtModified这2个字段的值的插入,后续将使用Xxx自动完成。

例如:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.tedu.csmall.product.mapper.AlbumMapper">

    <!-- int insert(Album album); -->
    <insert id="insert">
        INSERT INTO pms_album (
            name, description, sort
        ) VALUES (
            #{name}, #{description}, #{sort}
        )
    </insert>

</mapper>

首次使用时,需要在application.properties中配置以上XML文件的位置:

# Mybatis的配置SQL的XML文件的位置
mybatis.mapper-locations=classpath:mapper/*.xml

至此,“插入相册数据”的功能开发完成!

然后,应该及时测试以上功能是否正确,可以在src/test/java下的根包下创建mapper.AlbumMapperTests测试类,

package cn.tedu.csmall.product.mapper;

import cn.tedu.csmall.product.pojo.entity.Album;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class AlbumMapperTests {

    @Autowired
    AlbumMapper mapper;

    @Test
    void testInsert() {
        Album album = new Album();
        album.setName("某电视的相册");
        album.setDescription("某电视的相册的描述");
        album.setSort(63);
        int rows = mapper.insert(album);
        System.out.println("rows = " + rows);
    }

}

在执行测试时,如果此前配置的@MapperScan有误,会出现如下错误:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cn.tedu.csmall.product.mapper.AlbumMapperTests': Unsatisfied dependency expressed through field 'mapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.tedu.csmall.product.mapper.AlbumMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

如果在XML文件中,<mapper>namespace属性值配置有误,或者<insert>节点的id属性值配置有误,或者在application.properties中没有正确的配置mybatis.mapper-locations属性,都将出现以下错误:

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): cn.tedu.csmall.product.mapper.AlbumMapper.insert

插入数据时获取自动编号的id

在配置<insert>节点时,配置useGeneratedKeyskeyProperty这2个属性,就可以得到自动编号的id,例如:

<!-- int insert(Album album); -->
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
<!-- 省略后续代码 -->

其中,useGeneratedKeys="true"表示“需要获取自动编号的键的值”,keyProperty="id"表示将得到的自动编号的id值放回到参数对象的id属性中去!

开发规范上,对于自动编号的表进行插入数据时,都应该配置这2个属性!

使用Mybatis删除数据

需求:根据id删除相册数据

需要执行的SQL语句大致是:

delete from pms_album where id=?

AlbumMapper接口中添加抽象方法:

int deleteById(Long id);

AlbumMapper.xml中配置以上抽象方法映射的SQL:

<delete id="deleteById">
    DELETE FROM pms_album WHERE id=#{id}
</delete>

完成后,在AlbumMapperTests中添加新的测试方法:

@Test
void testDeleteById() {
    Long id = 1L;
    int rows = mapper.deleteById(id);
    System.out.println("rows = " + rows);
}

以上就是小编给大家总结的Mybatis框架知识!记得巩固哦!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值