Mybatis 一文速通 节约学习或复习成本

news2024/9/21 16:26:10

目录

1、简介

1.1、什么是Mybatis

1.2、持久化

1.3持久层

1.4为什么需要Mybatis?

2、第一个Mybatis程序

2.1、搭建环境

2.2、创建一个模块

2.3、编写代码

2.4、测试

3、CRUD

1、namespace

2、select

3、insert

4、update

5、delete

6、常见错误分析

7、万能Map

8、思考题

4、配置解析

1、核心配置文件

2、环境配置(environments)

3、属性(properties)

4、类型别名(typeAliases)

5、设置(settings)

7、映射器(mappers)

8、生命周期和作用域

5、解决属性名和字段名不一致的问题

1、问题

2、ResultMap

6、日志

6.1、日志工厂

6.2、Log4j

7、分页

7.1、使用Limit的分页

7.2、RowBounds分页

7.3、分页插件

8、使用注解开发

8.1、面向接口编程

8.2、使用注解开发

8.3、CRUD

9、Lombok

10、多对一处理

测试环境搭建

按照查询嵌套处理

按照结果嵌套处理

11、一对多处理

环境搭建

按照结果嵌套处理

按照查询嵌套处理

小结

12、动态SQL

搭建环境

IF

choose (when, otherwise)

trim (where, set)

SQL片段

Foreach

13、缓存

13.1、简介

13.2、Mybatis缓存

13.3、一级缓存

13.4、二级缓存

13.5、缓存原理

13.6、自定义缓存-Ehcache

程序错误整理

1、UTF-8和UTF8

2、IDEA单元测试执行查询功能新增数据问题


环境:

  • JDK 1.8
  • Mysql 5.7
  • maven 3.6.1
  • IDEA

回顾:

  • JDBC
  • MySQL
  • Java基础
  • Maven
  • Junit

SSM框架:配置文件的,最好的方式:看官网文档;

Mybatis官方文档:mybatis – MyBatis 3 | Introduction

1、简介

1.1、什么是Mybatis

  • MyBatis 是一款优秀的持久层框架
  • 它支持自定义 SQL、存储过程以及高级映射。
  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
  • MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。
  • 2013年11月迁移到Github。

如何获得Mybatis?

  • Maven:https://mvnrepository.com/search?q=mybatis
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.9</version>
</dependency>
  • GitHub链接:https://github.com/mybatis/mybatis-3

1.2、持久化

数据持久化

  • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
  • 内存:断电即失
  • 数据库(jdbc)、io文件持久化。
  • 生活:冷藏,罐头。

为什么需要持久化?

  • 有一些对象,不能让他丢失。
  • 内存太贵了

1.3持久层

Dao层,Service层,Controller层……

  • 完成持久化工作的代码块
  • 层界限十分明显

1.4为什么需要Mybatis?

  • 帮助程序员将数据存入数据库中。
  • 方便。
  • 传统的JDBC的代码太复杂了。简化。框架。自动化。
  • 不用Mybatis也可以。更容易上手。技术没有高低之分
  • 优点
    • 简单易学
    • 灵活
    • sql和代码的分离,提高了可维护性
    • 提供映射标签,支持对象与数据库的orm字段关系映射
    • 提供对象关系映射标签,支持对象关系组件维护
    • 提供xml标签,支持编写动态sql

最重要的一点:使用的人多!

2、第一个Mybatis程序

思路:搭建环境 --> 导入Mybatis --> 编写代码 --> 测试!

2.1、搭建环境

搭建数据库

create database `mybatis`;

use `mybatis`;

create table `user`(
	`id` int(20) not null,
	`name` varchar(30) default null,
	`pwd` varchar(30) default null,
	primary key(`id`)
)engine=innodb default charset=utf8;

insert into user(`id`,`name`,`pwd`) values 
(1,"狂神","123456"),
(2,"张三","123456"),
(3,"李四","123456");

新建项目

  1. 新建一个普通的maven项目。
  2. 删除src,作为父工程,maven修改路径。
  3. 导入maven依赖
<!--mysql驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.46</version>
</dependency>
<!--mybatis-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>
<!--Junit-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

2.2、创建一个模块

  • 编写mybatis核心配置文件

注意:useSSL=true 会报错

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="yjx123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>
  • 连接本地数据库

连接本地数据库出错误

解决方法: 在Advanced中将serverTimezone设置成Hongkong即可

在此查看数据库信息。

  • 编写mybatis工具类
//sqlSessionFactory --> sqlSession
public class MybatisUtils {

    //提升作用域
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //使用mybatis的第一步:获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    //SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

2.3、编写代码

  • 实体类

  • Dao接口
public interface UserDao {
    List<User> getUserList();
}
  • 接口实现类(由原来的UserDaoImpl转变为一个Mapper配置文件)
<?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">
<!--namespace绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.kuang.dao.UserDao">
    <!--id对应方法名字-->
    <!--resultType对应返回类型-->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user
    </select>
</mapper>

2.4、测试

注意点:src下的xml文件扫描不到

解决:

<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <includes>
        <include>**/*.properties</include>
        <include>**/*.xml</include>
      </includes>
      <filtering>true</filtering>
    </resource>
    <resource>
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.properties</include>
        <include>**/*.xml</include>
      </includes>
      <filtering>true</filtering>
    </resource>
  </resources>
</build>

MapperRegistry是什么?

核心配置文件中注册mappers

  • junit测试
public void test(){

    //第一步:获取的SqlSession对象
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    try {
        //方式一:getMapper 、 执行SQL
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();

        //方式二:
        // List<User> userList = sqlSession.selectList("com.kuang.dao.UserDao.getUserList");
        for (User user : userList){
            System.out.println(user);
        }
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        //关闭SqlSession
        sqlSession.close();

    }

}
  • 入门查询步骤

可能遇到的问题

  1. 配置文件没有注册
  2. 绑定接口错误
  3. 方法名不对
  4. 返回类型不对
  5. Maven导出资源问题

3、CRUD

注意:增删改的返回值都是受影响的行数。

insert标签没有resultType属性,返回boolean或者插入成功的数量(行数),执行失败则报错,不会返回

update标签没有resultType属性,返回boolean或者符合执行条件的数量(行数),执行失败则报错,不会返回

delete标签没有resultType属性,返回boolean或者符合执行条件的数量(行数),执行失败则报错,不会返回

insert对应的方法返回值为插入数据库的条数(如上,每次插入一条数据,所以每次addUser()都是返回1)

update对应的方法返回值为匹配数据库的条数(不论最终是否对数据进行了修改,只要某条记录符合匹配条件,返回值就加1)

1、namespace

namespace中的包名要和Dao/mapper接口的包名一致!

2、select

选择、查询语句

  • id:就是对应的namespace中的方法名;
  • resultType:sql语句执行的返回值;
  • parameterType:参数类型;

注:

  1. id是数据库表中的字段
  2. #{id}是你程序获取的一个参数,例如:#{id}为12
    这样就形成了你最终的 SQL语句 select * from userinfo where id=12

  1. 编写接口
//根据id查询用户
User getUserById(int id);
  1. 编写对应的mapper中的sql语句
<select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
  select * from mybatis.user where id = #{id}
</select>
  1. 测试
@Test
public void addUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    int res = mapper.addUser(new User(4, "男神", "458269"));
    if (res > 0) {
        System.out.println("插入成功!");
    }
    //提交事务
    sqlSession.commit();

    sqlSession.close();
}

3、insert

<insert id="addUser" parameterType="com.kuang.pojo.User" >
  insert into mybatis.user (id,name,pwd) value (#{id},#{name},#{pwd});
</insert>

4、update

<update id="updateUser" parameterType="com.kuang.pojo.User">
  update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}
</update>

5、delete

<delete id="deleteUser" parameterType="int">
  delete from mybatis.user where id=#{id}
</delete>

注意点:

  • 增删改需要提交事务!
//增删改需要提交事务
@Test
public void addUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    int res = mapper.addUser(new User(4, "男神", "458269"));
    if (res > 0) {
        System.out.println("插入成功!");
    }
    //提交事务
    sqlSession.commit();
    
    sqlSession.close();
}

6、常见错误分析

  1. 标签不能匹配错
  2. resources绑定mapper,需要使用路径
  3. 程序配置文件必须符合规范
  4. NullPointerException,没有注册到
  5. 源代码存在中文乱码,输出的xml文件中存在中文乱码问题
  6. maven资源没有导出问题

7、万能Map

假设,我们的实体类,或者数据库中的表、字段或者参数过多,我们应当考虑使用Map!

<!--对象中的属性可以直接取出来,传递Map的Key-->
<insert id="addUser2" parameterType="map" >
    insert into mybatis.user (id,name,pwd) value (#{userid},#{username},#{password});
</insert>
//万能的Map
int addUser2(Map<String,Object> map);
@Test
public void addUser2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    Map<String, Object> map = new HashMap<>();
    map.put("userid",5);
    map.put("username","hello");
    map.put("password","888888");
    mapper.addUser2(map);
    sqlSession.commit();
    sqlSession.close();
}

Map传递参数,直接在sql中取出key即可! 【parameterType="map"】

对象传递参数,直接在sql中取对象的属性即可! 【parameterType="Object"】

只有一个基本参数的情况下,可以直接在sql中取到! 【还可以不写】

多个参数用Map,或者注解

8、思考题

模糊查询怎么写?

  1. java代码执行的时候,传递通配符% %
List<User> userlist = mapper.getUserLike("%李%");
  1. 在sql拼接中使用通配符!
select * from mybatis.user where name like "%"#{value}"%";

4、配置解析

1、核心配置文件

  • mybatis-config.xml
  • Mybatis的配置文件包含了会深深影响Mybatis行为的设置和属性信息。
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

2、环境配置(environments)

MyBatis 可以配置成适应多种环境

不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

学会使用配置多套运行环境

Mybatis默认的事务管理器就是JDBC,连接池:POOLED

3、属性(properties)

我们可以通过properties属性来实现引用配置文件

这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.properties】

编写一个配置文件

url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8

在核心配置文件中引入

<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
    <!--引入外部配置文件-->
    <properties resource="db.properties"/>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
<!--                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>-->
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
<!--        <environment id="test">-->
<!--            <transactionManager type="JDBC"/>-->
<!--            <dataSource type="POOLED">-->
<!--                <property name="driver" value="com.mysql.jdbc.Driver"/>-->
<!--                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>-->
<!--                <property name="username" value="root"/>-->
<!--                <property name="password" value="yjx123"/>-->
<!--            </dataSource>-->
<!--        </environment>-->
    </environments>
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=yjx123

  • 可以直接引入外部文件【mybatis-config.xml】引用【db.properties】
  • 可以在其中增加一些属性配置【mybatis-config.xml】中直接写property
  • 如果两个文件有同一个字段,优先使用外部配置文件的!

4、类型别名(typeAliases)

  • 类型别名可为 Java 类型设置一个缩写名字。
  • 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
<!--可以给实体类起别名-->
<typeAliases>
  <typeAlias type="com.kuang.pojo.User" alias="User"/>
</typeAliases>
  • 也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean。

扫描实体类的包,它的默认别名就是这个类的,首字母小写。

<typeAliases>
  <package name="com.kuang.pojo"/>
</typeAliases>

在实体类比较少的情况下,使用第一种方式。

如果实体类十分多,使用第二种包名。

第一种可以Diy别名,第二种则不行,如果非要改,需要在实体上增加注解

import org.apache.ibatis.type.Alias;
//实体类
@Alias("user")
public class User {}

5、设置(settings)

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。

6、其他配置

  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins(插件)
    • mybatis-generator-core
    • mybatis-plus
    • 通用mapper

7、映射器(mappers)

MapperRegistry:注册绑定我们的Mapper文件;

方式一:

<!--每一个Mapper.xml都需要在mybatis核心配置文件中注册!-->
<mappers>
  <mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>

方式二:使用class文件绑定注册

<mappers>
  <mapper class="com.kuang.dao.UserMapper"/>
</mappers>

注意点:

  • 接口和他的Mapper配置文件必须同名
  • 接口和他的Mapper配置文件必须在同一个包下

方式三:使用扫描包进行注入绑定

<mappers>
   <package name="com.kuang.dao"/>
</mappers>

注意点同方式二

练习时间:

  • 将数据库配置文件外部引入
  • 实体类别名
  • 保证UserMapper接口和UserMapper.xml改为一致!并且放在同一个包下!

8、生命周期和作用域

生命周期,和作用域,是至关重要的,因为错误的使用会导致非常严重的并发问题

SqlSessionFactoryBuilder:

  • 一旦创建了SqlSessionFactory,就不需要SqlSessionFactoryBuilder了;
  • 局部变量

SqlSessionFactory:

  • 说白了就是可以想象为:数据库连接池
  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
  • 因此 SqlSessionFactory 的最佳作用域是应用作用域。
  • 最简单的就是使用单例模式或者静态单例模式。

SqlSession:

  • 连接到连接池的一个请求!
  • 关闭
  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
  • 用完之后需要赶紧关闭,否则资源被占用!

这里面的每一个Mapper,就代表一个具体的业务!

5、解决属性名和字段名不一致的问题

1、问题

数据库中的字段与项目实体类中不一致的情况:

测试出现问题

解决方法:

  • 起别名
<select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
  select id,name,pwd as password from mybatis.user where id = #{id}
</select>

2、ResultMap

结果集映射

id name pwd

id name password

<!--结果集映射-->
<resultMap id="UserMap" type="User">
  <!--column对应数据库中的字段,property对应实体类中的属性-->
  <result column="id" property="id"/>
  <result column="name" property="name"/>
  <result column="pwd" property="password"/>
</resultMap>

<select id="getUserById" resultMap="UserMap">
  select * from mybatis.user where id = #{id}
</select>
  • resultMap 元素是 MyBatis 中最重要最强大的元素。
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
  • ResultMap 的优秀之处,虽然你已经对它相当了解了,但是根本就不需要显示地用到他们。

6、日志

6.1、日志工厂

如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的助手!

曾今:sout、debug

如今:日志工厂

  • SLF4J
  • LOG4J(3.5.9 起废弃)【掌握】
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING 【掌握】
  • NO_LOGGING

在Mybatis中具体使用哪一个日志实现,在设置中设定!

STDOUT_LOGGING 标准日志输出

在mybatis核心配置文件中,配置我们的日志!

<settings>
  <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

6.2、Log4j

什么是Log4j?

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件。
  • 我们也可以控制每一条日志的输出格式;
  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
  • 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

  1. 先导入Log4j的包
<dependencies>
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
  </dependency>
</dependencies>
  1. log4j.properties
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
  1. 配置log4j为日志的实现
<settings>
  <setting name="logImpl" value="LOG4J"/>
</settings>
  1. Log4j的使用!直接测试运行刚才的查询。

简单使用

  1. 在要使用Log4j的类中,导入包 import org.apache.log4j.Logger;
  2. 日志对象,参数为当前类的class

static Logger logger = Logger.getLogger(UserMapperTest.class);

  1. 日志级别
logger.info("info:进入了testLog4j");
logger.debug("error:进入了testLog4j");
logger.error("error:进入了testLog4j");

7、分页

思考:为什么要分页?

  • 减少数据的处理量

7.1、使用Limit的分页

语法:select * from user limit startIndex,pageSize;
select * from user limit 3;  #[0,n]

使用mybatis实现分页,核心SQL

  1. 接口
//分页
List<User> getUserByLimit(Map<String,Integer> map);
  1. Mapper.xml

注:此处的resultMap需要使用到结果集映射

<!--  分页实现查询  -->
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
  select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
  1. 测试
@Test
public void getUserByLimit(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String, Integer> map = new HashMap<>();
    map.put("startIndex",0);
    map.put("pageSize",2);
    List<User> userList = mapper.getUserByLimit(map);
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

7.2、RowBounds分页

不再使用Sql实现分页

  1. 接口
List<User> getUserByRowBounds();
  1. mapper.xml
<select id="getUserByRowBounds" resultMap="UserMap">
  select * from mybatis.user
</select>
  1. 测试
@Test
public void getUserByRowBounds(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    //RowBounds实现
    RowBounds rowBounds = new RowBounds(1, 2);
    //通过Java代码层面实现分页
    List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRowBounds",null,rowBounds);
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

7.3、分页插件

mybatis插件pagehelper

了解即可,万一以后公司的架构师,说要使用,你需要知道它是什么东西!

8、使用注解开发

8.1、面向接口编程

  • 大家事前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
  • 根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实训,大家都遵守共同的标准,是的开发变得容易,规范性更好
  • 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
  • 而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是按照这种思想来编程。

关于接口的理解

  • 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
  • 接口的本身反映了系统设计人员对系统的抽象理解。
  • 接口应有两类:
    • 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
    • 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);
  • 一个个体有可能有很多个抽象面。抽象体与抽象面是有区别的。

三个面向区别

  • 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法;
  • 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现;
  • 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构。

8.2、使用注解开发

  1. 注解在接口上实现
public interface UserMapper {
    @Select("select * from user")
    List<User> getUsers();
}
  1. 需要在核心配置文件中绑定接口!
<!--绑定接口-->
<mappers>
  <mapper class="kuang.dao.UserMapper"/>
</mappers>
  1. 测试

本质:反射机制实现

底层:动态代理!

Mybatis详细执行流程!

8.3、CRUD

我们可以再工具类创建的时候实现自动提交事务!

return sqlSessionFactory.openSession(true);

设置为true

//sqlSessionFactory --> sqlSession
public class MybatisUtils {
    //提升作用域
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //使用mybatis的第一步:获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    //SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }
}

编写接口,增加注解

import org.apache.ibatis.annotations.*;

public interface UserMapper {

    @Select("select * from user")
    List<User> getUsers();

    //方法存在多个参数,所有的参数前面必须添加@Param("")注解
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") int id);

    @Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
    int addUser(User user);

    @Update("update user set name=#{name},pwd=#{password} where id = #{id}")
    int updateUser(User user);

    @Delete("delete from user where id = #{uid}")
    int deleteUser(@Param("uid") int id);
}

测试类

【注意:我们必须要将接口配置到核心配置文件中!】-->映射器

mybatis-config.xml中绑定接口

<!--绑定接口-->
<mappers>
<mapper class="kuang.dao.UserMapper"/>
</mappers>

关于@Param()注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议大家都加上!
  • 我们在SQL中引用的就是我们这里的@Param()中设定的属性名!

@Delete("delete from user where id = #{uid}")
int deleteUser(@Param("uid") int id);

#{} ${}区别

9、Lombok

  • java library
  • plugs
  • build tools
  • with one annotation your class

使用步骤:

  1. 在IDEA中安装Lombok插件!

  1. 在项目中导入lombok的jar包
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
</dependency>
  1. 注解
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows

说明:

@Date:无参构造、get、set、toString、hashcode、equals
@AllArgsConstructor:有参构造
@NoArgsConstructor:无参构造

@Getter放在类上所有的属性都有get方法,放在一个属性上只有当前属性拥有。

10、多对一处理

多对一:

  • 多个学生,对应一个老师
  • 对于学生这边而言,关联……多个学生,关联一个老师【多对一】
  • 对于老师而言,集合,一个老师有很多学生【一对多】

SQL:

use mybatis

create table `teacher`(
  `id` int(10) not null,
	`name` varchar(30) default null,
	primary key (`id`)
) engine=innodb default charset=utf8

insert into teacher(`id`,`name`) values (1,"秦老师");

create table `student`(
  `id` int(10) not null,
	`name` varchar(30) default null,
	`tid` int(10) default null,
	primary key (`id`),
	key `fktid` (`tid`),
	constraint `fktid` foreign key (`tid`) references `teacher` (`id`)
) engine=innodb default charset=utf8

insert into `student` (`id`,`name`,`tid`) values (1,"小明",1);
insert into `student` (`id`,`name`,`tid`) values (2,"小红",1);
insert into `student` (`id`,`name`,`tid`) values (3,"小张",1);
insert into `student` (`id`,`name`,`tid`) values (4,"小李",1);
insert into `student` (`id`,`name`,`tid`) values (5,"小王",1);

测试环境搭建

  1. 导入lombok
  2. 新建实体类Teacher、Student
  3. 建立Mapper接口
public interface TeacherMapper {
    @Select("select * from teacher where id = #{tid}")
    Teacher getTeacher(@Param("tid") int id);
}
  1. 建立Mapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.kuang.dao.TeacherMapper">

</mapper>
  1. 在核心配置文件中绑定注册我们的Mapper接口或者文件!【方式很多,随心选】
<mappers>
  <mapper class="com.kuang.dao.TeacherMapper"/>
  <mapper class="com.kuang.dao.StudentMapper"/>
</mappers>
  1. 测试查询是否能够成功!

按照查询嵌套处理

<mapper namespace="com.kuang.dao.StudentMapper">
    <!--
        思路:
           1.查询所有的学生信息
           2.根据查询出来的学生的tid,寻找对应的老师! 子查询
    -->
    <select id="getStudent" resultMap="StudentTeacher">
        select * from student;
    </select>
    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--复杂的属性,我们需要单独处理 对象:association 集合:collection-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id = #{id};
    </select>
</mapper>

按照结果嵌套处理

<!--按照结果嵌套处理:查询写完之后,再写里面对应的关系-->

<select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.name tname
    from student s,teacher t
    where s.tid = t.id;
</select>

<resultMap id="StudentTeacher2" type="Student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tname"/>
    </association>
</resultMap>

回顾MySQL多对一查询:

  • 子查询
  • 联表查询

11、一对多处理

比如:一个老师拥有多个学生!

对于老师而言,就是一对多关系

环境搭建

与10同

实体类

@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}
@Data
public class Teacher {
    private int id;
    private String name;
    //一个老师拥有多个学生
    private List<Student> students;
}

按照结果嵌套处理

<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
  select s.id sid,s.name sname,t.name tname,t.id tid
  from student s,teacher t
  where s.tid = t.id and t.id = #{tid};
</select>
<resultMap id="TeacherStudent" type="Teacher">
  <result property="id" column="tid"/>
  <result property="name" column="tname"/>
  <!--
      复杂的数据类型,我们需要单独处理 对象:association 集合:collection
      javaType=""指定属性的类型!
      集合中的泛型信息,我们使用ofType获取
   -->
  <collection property="students" ofType="Student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <result property="tid" column="tid"/>
  </collection>
</resultMap>

按照查询嵌套处理

<select id="getTeacher2" resultMap="TeacherStudent2">
  select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
  <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
  select * from student where tid = #{tid}
</select>

小结

  1. 关联 - association 【多对一】
  2. 集合- collection 【一对多】
  3. javaType & ofType
    1. JavaType 用来指定实体类中属性的类型
    2. ofType 用来指定映射到List或者集合中pojo类型,泛型中的约束类型

注意点:

  • 保证SQL的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性名和字段的问题
  • 如果问题不好排查错误,可以使用日志,建议使用Log4j

慢SQL 1s 10000s

面试高频

  • Mysql引擎
  • InnoDB底层原理
  • 索引
  • 索引优化

多表联查MP

@Repository
public interface BlogMapper extends BaseMapper<Blog> {
    /**
     * 静态查询
     */
    @Select("SELECT t_user.user_name " +
            " FROM t_blog, t_user " +
            " WHERE t_blog.id = #{id} " +
            "     AND t_blog.user_id = t_user.id")
    String findUserNameByBlogId(@Param("id") Long id);
     * 动态查询
    @Select("SELECT * " +
            " ${ew.customSqlSegment} ")
    IPage<BlogVO> findBlog(IPage<BlogVO> page, @Param("ew") Wrapper wrapper);
}
///

@ApiOperation("静态查询")
@GetMapping("staticQuery")
public String staticQuery() {
    return blogMapper.findUserNameByBlogId(1L);
}
@ApiOperation("动态查询")
@GetMapping("dynamicQuery")
public IPage<BlogVO> dynamicQuery(Page<BlogVO> page, String nickName, String title) {
    QueryWrapper<BlogVO> queryWrapper = new QueryWrapper<>();
    queryWrapper.like(StringUtils.hasText(nickName), "t_user.nick_name", nickName);
    queryWrapper.like(StringUtils.hasText(title), "t_blog.title", title);
    queryWrapper.eq("t_blog.deleted_flag", 0);
    queryWrapper.eq("t_user.deleted_flag", 0);
    queryWrapper.apply("t_blog.user_id = t_user.id");
    return blogMapper.findBlog(page, queryWrapper);
}

12、动态SQL

什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句

利用动态 SQL,可以彻底摆脱这种痛苦。

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。
在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3
替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

if
choose (when, otherwise)
trim (where, set)
foreach

搭建环境

CREATE TABLE `blog`(
  `id` varchar(50) NOT NULL COMMENT "博客id",
  `title` varchar(100) NOT NULL COMMENT "博客标题",
  `author` varchar(30) NOT NULL COMMENT "博客作者",
  `create_time` datetime NOT NULL COMMENT "创建时间",
  `views` int(30) NOT NULL COMMENT "浏览量"
) ENGINE=InnoDB DEFAULT CHARSET=utf8

创建一个基础工程

  1. 导包
  2. 编写配置文件
  3. 编写实体类

@SuppressWarnings("all")//抑制警告

@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}
  1. 编写实体类对应Mapper接口和Mapper.xml文件

IF

<select id="queryBlogIF" parameterType="map" resultType="blog">
  select * from mybatis.blog where 1=1
  <if test="title != null">
    and title = #{title}
  </if>
  <if test="author != null">
    and author = #{author}
  </if>
</select>

choose (when, otherwise)

<select id="queryBlogChoose" parameterType="map" resultType="blog">
  select * from mybatis.blog
  <where>
    <choose>
      <when test="title != null">
        title = #{title}
      </when>
      <when test="author != null">
        and author = #{author}
      </when>
      <otherwise>
        and views = #{views}
      </otherwise>
    </choose>
  </where>
</select>

trim (where, set)

select * from mybatis.blog
<where>
  <if test="title != null">
    title = #{title}
  </if>
  <if test="author != null">
    and author = #{author}
  </if>
</where>
<update id="updateBlog" parameterType="map">
  update mybatis.blog
  <set>
    <if test="title != null">
      title = #{title},
    </if>
    <if test="author != null">
      author = #{author}
    </if>
  </set>
  where id = #{id}
</update>

所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码

SQL片段

有的时候,我们可能会将一些功能的部分抽取出来,方便复用!

  1. 使用SQL标签抽取公共的部分
<sql id="if-title-author">
  <if test="title != null">
    title = #{title}
  </if>
  <if test="author != null">
    and author = #{author}
  </if>
</sql>
  1. 在需要使用的地方使用include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="blog">
  select * from mybatis.blog
  <where>
    <include refid="if-title-author"></include>
  </where>
</select>

注意事项:

  • 最好基于单表来定义SQL片段!
  • 不要存在where标签

Foreach

select * from user where 1 = 1 and 
(id = 1 or id = 2 or id = 3)

==
    <foreach item="id" collection="ids"
        open="(" separator="or" close=")" >
          #{id}
    </foreach>

foreach

<!--
    select * from mybatis.blog where 1=1 and (id=1 or id=2 or id=3)
    我们现在传递一个万能的Map,这map中可以存在一个集合!
 -->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
  select * from mybatis.blog
  <where>
    <foreach collection="ids" item="id" open="and (" close=")" separator="or">
      id = #{id}
    </foreach>
  </where>
</select>

动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了。

建议:

  • 先在Mysql中写出完整的SQL在对应的去修改成为我们的动态SQL实现通用即可!

13、缓存

13.1、简介

查询: 连接数据库,耗资源!
    一次查询的结果,给它暂存在一个可以直接取到的地方!-->内存 : 缓存
我们在此查询相同数据的时候,直接走缓存,就不用走数据库了
  1. 什么是缓存 [Cache] ?
    • 存在内存中的临时数据。
    • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
  1. 为什么使用缓存?
    • 减少和数据库的监护次数,减少系统开销,提高系统效率。
  1. 什么样的数据能使用缓存?
    • 经常查询并且不经常改变的数据。【可以使用缓存】

13.2、Mybatis缓存

  • Mybatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
  • Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存
    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,它是基于namespace级别的缓存。
    • 为了提高扩展性,Mybatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存。

13.3、一级缓存

  • 一级缓存也叫本地缓存:SqlSession
    • 与数据库同一次会话期间查询到的数据会放在本地缓存中。
    • 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库。

测试步骤

  1. 开启日志!
  2. 测试在一个Session中查询两次相同的记录
  3. 查看日志输出

缓存失效的情况:

  1. 查询不同的东西
  2. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
  3. 查询不同的Mapper.xml
  4. 手动清理缓存

小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!

一级缓存相当于一个Map,

13.4、二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
    • 如果会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
    • 新的会话查询信息,就可以从二级缓存中获取内容;
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中;

步骤:

  1. 开启全局缓存
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
  1. 在要使用二级缓存的Mapper中开启
<!--在当前Mapper.xml中使用二级缓存-->
<cache/>

也可以自定义参数

<!--在当前Mapper.xml中使用二级缓存-->
<cache eviction="FIFO"
       flushInterval="60000"
       size="512"
       readOnly="true"/>
  1. 测试
    1. 问题:我们需要将实体类序列化!否则就会报错!

小结:

  • 只要开启了二级缓存,在同一个Mapper下就有效
  • 所有的数据都会先放在一级缓存中;
  • 只有当会话提交,或者关闭的时候,才会提交到二级缓冲中!

13.5、缓存原理

13.6、自定义缓存-Ehcache

Ehcache是一种广泛使用的开源Java分布式缓存,主要面向通用缓存

要在程序中使用Ehcache,先要导包!

<dependency>
  <groupId>org.mybatis.caches</groupId>
  <artifactId>mybatis-ehcache</artifactId>
  <version>1.1.0</version>
</dependency>

在mapper中指定使用我们的ehcache缓存实现!

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

ehcache.xml

<?xml version="1.0" encoding="UTF-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">

    <diskStore path="./tmpdir/Tmp_EhCache"/>

    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"/>

    <cache
            name="cloud_user"
            eternal="false"
            maxElementsInMemory="5000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="1800"
            memoryStoreEvictionPolicy="LRU"/>
</ehcache>

Redis数据库来做缓存! K-V

程序错误整理

1、UTF-8和UTF8

org.apache.ibatis.builder.BuilderException: Error creating document instance.

  1. 解决方案

方案一:

在pom.xml文件中添加如下代码:

<properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

方案二:

将所有的xml文件中UTF-8设置为UTF8

<?xml version="1.0" encoding="UTF8" ?>

  1. 原因分析

这个问题的主要原因是xml文件中声明的编码与xml文件本身保存时的编码不一致。 比如:你的声明是

<?xml version="1.0" encoding="UTF-8"?>

但是却以ANSI格式编码保存,尽管并没有乱码出现,但是xml解析器是无法解析的。 解决办法就是重新设置xml文件保存时的编码与声明的一致。

PS:pom.xml添加代码若运行成功后,删除添加的代码,依然能再次运行成功!

2、IDEA单元测试执行查询功能新增数据问题

原因
单元测试时会先build进行编译,而build的时候会执行你项目中的所有加了@Test的方法。

导致在使用单元测试的时候,当执行一次后,数据库中插入了两条一样的数据

解决方法:

方法一:打钩选择取消跳过单元测试

方法二:在pom中配置

<build><!-- maven中跳过单元测试 -->
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <skip>true</skip>
            </configuration>
        </plugin>
    </plugins>
</build>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2057938.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Linux进程间通信学习记录(IPC 机制、共享内存以及信号灯集)

0.System V IPC机制&#xff1a; ①.IPC对象包含&#xff1a;共享内存、消息队列和信号灯集。 ②.每个IPC对象有唯一的ID。 ③.IPC对象创建后一直存在&#xff0c;直到被显示地删除。 ④.每一个IPC对象有一个关联的KEY。&#xff08;其他进程通过KEY访问对应的IPC对象&#xff…

SpringCloud远程调用为啥要采用HTTP,而不是RPC?

关于SpringCloud远程调用采用HTTP而非RPC。 1. 首先SpringCloud开启Web服务依赖于内部封装的Tomcat容器&#xff0c;而今信息飞速发展&#xff0c;适应大流量的微服务&#xff0c;采用Tomcat处理HTTP请求&#xff0c;开发者编写Json作为资源传输&#xff0c;服务器做出相应的响…

Flutter【01】状态管理

声明式编程 Flutter 应用是 声明式 的&#xff0c;这也就意味着 Flutter 构建的用户界面就是应用的当前状态。 当你的 Flutter 应用的状态发生改变时&#xff08;例如&#xff0c;用户在设置界面中点击了一个开关选项&#xff09;你改变了状态&#xff0c;这将会触发用户界面…

flume--数据从kafka到hdfs发生错误

解决&#xff1a; #1.将flume自带的依赖删除 mv /opt/installs/flume1.9/lib/guava-11.0.2.jar /opt/installs/flume1.9/lib/guava-11.0.2.jar.bak #2.将hadoop的依赖发送到flume下 cp /opt/installs/hadoop3.1.4/share/hadoop/common/lib/guava-27.0-jre.jar /opt/installs/f…

招商期货:以超融合支撑期货重要业务,承载80%信创系统

招商期货有限公司&#xff08;以下简称“招商期货”&#xff09;成立于 1993 年&#xff0c;是招商证券股份有限公司的全资子公司&#xff0c;注册资本 35.98 亿元&#xff0c;是中国首批券商全资控股期货公司。 随着数字化进程快速推进、交易模式不断创新&#xff0c;系统建设…

Axure设计之三级菜单导航教程(中继器)

中继器作为复杂的元件&#xff0c;通常被用来制作“高保真”的动态原型&#xff0c;以达到良好的视觉效果和交互效果。本文将教大家通过AxureRP9工具如何使用中继器设计三级菜单导航。 一、案例效果 原型预览&#xff1a;https://1zvcwx.axshare.com 主要效果&#xff1a; 1…

异步交互技术Ajax-Axios

目录 一、同步交互和异步交互 二、Ajax 1.概述 2.如何实现ajax请求 三、异步传输数据乱码的问题 regist.html页面代码 服务端代码处理 四、Axios 1. Axios的基本使用 &#xff08;1&#xff09;引入Axios文件 &#xff08;2&#xff09;使用Axios发送请求&#xff0…

Chapter 42 递归

欢迎大家订阅【Python从入门到精通】专栏&#xff0c;一起探索Python的无限可能&#xff01; 文章目录 前言一、基本概述二、案例分析 前言 递归是一种在编程中广泛使用的技术&#xff0c;通过让函数调用自身来逐步解决问题。本章详细讲解了 Python 中递归的基本原理以及应用场…

SSRF服务器请求伪造

目录 SSRF服务器请求伪造 一、SSRF漏洞概述 二、SSRF常见的函数 1、file_get_contents() 2、fsockopen() 3、exec()发送GET请求 4、exec()发送POST请求 三、SSRF主要危害 1、先准备以下脚本 2、读取文件和信息 3、内网扫描 4、获取指纹信息 四、SSRF漏洞挖掘技巧 …

Nginx---Web服务器

简介 介绍nginx中Web服务器的相关配置 环境配置 mkdir /data/web/html -p mkdir /data/web/html/test{1..5} echo test1 > /data/web/html/test1/index.html echo test2 > /data/web/html/test2/index.html echo test3 > /data/web/html/test3/index.html echo tes…

FPGA时序约束

目录 一、概述二、时序分析基本概念时钟抖动时钟偏差时钟不确定性Clock Uncertainty同步电路和异步电路建立时间和保持时间发起沿和采样沿关键路径 三、时序分析的基本公式时序分析的基本路径数据到达时间和时钟到达时间建立时间的裕量&#xff08;Setup slack&#xff09;保持…

STM32CubeMX 配置串口通信 HAL库

一、STM32CubeMX 配置串口 每个外设生成独立的 ’.c/.h’ 文件 不勾&#xff1a;所有初始化代码都生成在 main.c 勾选&#xff1a;初始化代码生成在对应的外设文件。 如 GPIO 初始化代码生成在 gpio.c 中。 二、重写fputc函数 ​ #include <stdio.h>#ifdef __GNUC__#def…

“LOCAL_LISTENER”参数导致业务无法连接数据库,文末附Oracle连接故障检查监听的排查流程

1. 背景及问题 今天在Oracle BCV技术[1]做数据同步&#xff0c;建立生产库的测试库&#xff0c;需要DBA配合同步前后的停库和起库。在同步完起库后&#xff0c;有部门反应同步好的测试库连接不上去。 2. 问题排查 以我当前的知识储备&#xff0c;能想到的可能就是以下几点进…

【NLP】注意力机制:规则、作用、原理、实现方式

文章目录 1、本章目标2、注意力机制介绍2.1、注意力概念2.2、注意力机制2.3、翻译举例 3、注意力计算规则3.1、打个比喻3.2、公式3.2.1、线性变换 点积注意力3.2.2、加性注意力3.2.3、点积注意力3.2.4、对比与总结3.2.5、bmm运算 4、注意力机制的作用5、注意力机制原理⭐5.1、…

基于java的美食信息推荐系统的设计与实现论文

摘 要 使用旧方法对美食信息推荐系统的信息进行系统化管理已经不再让人们信赖了&#xff0c;把现在的网络信息技术运用在美食信息推荐系统的管理上面可以解决许多信息管理上面的难题&#xff0c;比如处理数据时间很长&#xff0c;数据存在错误不能及时纠正等问题。这次开发的美…

Linux系统-vi/vim编辑器权限管理文档处理三剑客

1.vi/vim文本编辑器 vim是vi的增强版&#xff0c;vi是系统自带的。以下命令在vi/vim中通用&#xff1a; 刚打开的默认模式 快捷键&#xff1a;gg 跳到文件开头&#xff0c;G 跳到文件最后一行。 快捷键&#xff1a;0 跳到行首&#xff0c;$ 跳到行尾。 快捷键&#xff1a;…

C++ | Leetcode C++题解之第355题设计推特

题目&#xff1a; 题解&#xff1a; class Twitter {struct Node {// 哈希表存储关注人的 Idunordered_set<int> followee;// 用链表存储 tweetIdlist<int> tweet;};// getNewsFeed 检索的推文的上限以及 tweetId 的时间戳int recentMax, time;// tweetId 对应发送…

vue3--定时任务cron表达式组件比较

## 背景&#xff1a; 之前使用vue2开发项目时&#xff0c;使用了cron组件&#xff0c;比较了两种组件的使用效果。现在需要把原有的vue2项目升级为vue3&#xff0c;需要对应的cron组件。 方案一&#xff0c;vue3-cron-plus 具体实现&#xff1a; 安装插件 npm install vue3-…

浅谈shell中的while true

目录 shell实现死循环你了解while true中的true吗重新认识true和falsewhile true存在的问题实现shell死循环的另一种方法 在shell中实现死循环&#xff0c;一般都会用 while true&#xff0c;那你知道执行while true时&#xff0c;进程都在做些什么吗&#xff1f; shell实现死…

云计算实训32——安装nginx(修改端口为8080)、roles基本用法、使用剧本安装nginx、使用roles实现lnmp

一、安装nginx并更改其端口 编辑hosts配置文件 [rootmo ~]# vim /etc/ansible/hosts 创建目录 [rootmo ~]# mkdir /etc/ansible/playbook 编辑配置文件 [rootmo ~]# vim /etc/ansible/playbook/nginx.yml 执行测试 [rootmo ~]# ansible-playbook /etc/ansible/playbook/n…