梦见你的名字 发表于 2024-8-30 11:20:07

框架 +【Mybatis】概述 以及 基础环境搭建

目录

什么是框架?
java后端框架包括
Mybatis概述
1、背景介绍
2、mybatis介绍
Mybatis环境搭建
1.创建一个maven项目
2.导入mysql数据库驱动包
   导入mybatis依赖的jar包
3.创建一个全局的mybatis配置文件 
4.创建数据库,创建表,准备数据
5.创建一个访问接口,定义方法
6.创建接口对应的映射文件,编写sql
创建完sql映射文件后还需要再全局配置文件中举行配置:
7.测试Mybatis

搭建补充:
1、安装一个MybatisX焦点全局配置文件
2、数据库链接池

参数传递
1、单个参数
直接传递
2、多个参数
使用@Param(“id”)注解绑定
传入复杂的对象,需要使用parameterType参数举行范例定义。
Mybatis基础操纵---增编削查
1、增长insert
2、删除delete
3、修改update
4、查找select
#{}和${}区别
1、底层实现不同
2、使用场景不同
单元测试
数据库事务
   1、简介
关联查询
1、直接多表关联査询出我们需要的数据
2、 嵌套查询,先查询主表(学生表)
对象映射
特殊符号处理
1、在 mybatis 中的 xml 文件,一些特殊符号需要转译:
2、使用   
数据缓存
什么是缓存? 
1、mybatis一级缓存
2、mybatis二级缓存
二级缓存的特点包括:

什么是框架?

框架就是对技能的封装,将基础的技能举行封装,让程序员可以快速的使用,进步开发服从。
java后端框架包括

   mybatis
            对jdbc举行封装
spring
           对整个java后端架构举行管理的
springweb
           对web层(servlet)举行封装
springboot
            对spring框架的搭建举行封装
Mybatis概述

1、背景介绍

mybatis原来是Apache下面的一个开源项目,名为ibayis.
2010年开发团队转移到谷歌旗下,改名为mybatis.
2、mybatis介绍

Mybatis是一款良好的数据长期层框架(dao层 数据访问层 数据长期层)
MyBatis对JDBC举行封装,MyBatis 制止了险些全部的 JDBC 代码手动设置参数以及手动映射结果集的操纵。
MyBatis将JDBC中的接口举行封装,提供它自己的类和接口实现。可以使用xml配置和注解的方式,将数据库中的记录主动映射到java对象中。
是一种ORM实现(对象关系映射)将可以主动将数据映射到对象中的这中框架,也称ORM框架
mybatis还提供了动态sql和数据缓存。
Mybatis环境搭建

1.创建一个maven项目

并在pom.xml文件中导入Mybatis所依赖的jar包,由于Mybatis是对JDBC代码举行了封装,以是还需要导入mysql数据库驱动包。
2.导入mysql数据库驱动包

           <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version>8.0.16</version>
        </dependency>
   导入mybatis依赖的jar包

           <dependency>
             <groupId>org.mybatis</groupId>
             <artifactId>mybatis</artifactId>
             <version>3.4.2</version>
        </dependency>
3.创建一个全局的mybatis配置文件 

右键resources目录,选择File,创建一个xml文件,此文件用来写Mybatis全局配置相关的代码,如图所示:
<?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>
<!--配置数据库连接相关信息-->
    <environments default="development"><!--work-->
      <environment id="development">
            <!--Mybatis手动提交,JDBC自动提交-->
            <transactionManager type="JDBC"/>
            <!--type="POOLED" 使用数据库链接池功能,默认创建了10个链接对象,减少频繁创建的链接对象-->
            <dataSource type="POOLED">
                <!--数据库链接配置-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/ssmdb?serverTimezone=Asia/Shanghai" />
                <property name="username" value="root" />
                <property name="password" value="root"/>
            </dataSource>
      </environment>
    </environments>
</configuration> ➱留意将参数修改为自己的数据库连接信息
https://i-blog.csdnimg.cn/direct/a071f483a9f74104b9005472409ada11.png
4.创建数据库,创建表,准备数据

5.创建一个访问接口,定义方法

https://i-blog.csdnimg.cn/direct/5134411ef6ae42c7a209ac92c6f51292.png
6.创建接口对应的映射文件,编写sql

<?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">
<!--sql映射文件主要写sql实现-->
<!--
   useGeneratedKeys="true":返回自增主键
   keyProperty="id":类中的属性
   keyColumn="id":数据库中的列
-->
<mapper namespace="com.ffyc.mybatispro.dao.AdminDao">
                                                                   <!-- keyProperty:类中的属性keyColumn:数据库中的列-->
    <insert id="insertAdmin" parameterType="Admin" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
                              <!-- 数据库中的列名                      Admin对象中的属性-->
      insert into admin(account,password,gender) values (#{account},#{password},#{gender})</insert>

    <update id="updateAdmin" parameterType="Admin">
      update admin set account=#{account},password=#{password} where id=#{id}</update>

    <select id="findAdminById" parameterType="int" resultType="Admin">
         select * from admin where id = #{id} </select>

    <select id="login" resultType="Admin">
      select * from admin where account=#{acc} and password=#{pwd}</select>

    <select id="login1" parameterType="Admin" resultType="Admin">
      select * from admin where account=#{account} and password=#{password}</select>
<!--select count(*) from admin where id &lt; 10-->
    <select id="findAdminCount" parameterType="int" resultType="int">
      select count(*) from admin where id <!]> 10 </select>

    <select id="findAdmins" resultType="Admin" parameterType="string">
         select * from admin order by ${orderColumn} desc</select>

    <select id="findAdminid" resultType="java.lang.Integer">
         select id from admin where account=#{account}</select>

    <select id="findAdmins1" resultType="Admin" parameterType="string">
         select * from admin</select>


    <resultMap id="adminMap" type="Admin">
      <id column="adminid" property="id"></id>
      <result column="account" property="account"></result>
    </resultMap>
    <select id="findAdmin"resultMap="adminMap">
      select id adminid,account from admin</select>

    <delete id="deleteAdmin" parameterType="int">
      delete from
                admin where id =#{id}</delete>

</mapper>
https://i-blog.csdnimg.cn/direct/1c89b247bc4c4c35afe3d4d9f384ebc4.png
创建完sql映射文件后还需要再全局配置文件中举行配置:

https://i-blog.csdnimg.cn/direct/92bda83ac580449f983e9ccc775ae3ea.png
7.测试Mybatis



搭建补充:

1、安装一个MybatisX焦点全局配置文件

https://i-blog.csdnimg.cn/direct/c71d4d193b424cd48582a5ada1d78df6.png

2、数据库链接池

        链接数据库后,每次访问数据库时都要创建一个Connection连接对象,并且用完之后关闭。一旦访问量一大,每次都要创建新的连接对象,用完关闭,比较耗时。
        使用数据库链接池,在池(聚集)中事先创建一些连接对象,在用户访问时,就直接从池中获取一个链接对象,用完不烧毁,还回到池中。这样就减少频仍创建烧毁链接对象。
https://i-blog.csdnimg.cn/direct/c023c659db4b4636850c6fdc58cae611.png
https://i-blog.csdnimg.cn/direct/548486d95fb4425fa6edeebddfd4e1d2.png


参数传递

三种方式
1、单个参数

直接传递

   
Admin findAdminById(int id);2、多个参数

使用@Param(“id”)注解绑定

   
Admin login(@Param("acc")String account, @Param("pwd")String password);https://i-blog.csdnimg.cn/direct/12f0cd874ddf404b8124de0bd85cfa5d.png 
传入复杂的对象,需要使用parameterType参数举行范例定义。

https://i-blog.csdnimg.cn/direct/edcc45f584ae40a2b24636f688d13bfc.png
   封装到对象中,通过对象中定义的属性传参。
Admin login1(Admin admin);//对象 Mybatis基础操纵---增编削查

1、增长insert

   void insertAdmin(Admin admin);<?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">
<!--sql映射文件主要写sql实现-->
<!--
   useGeneratedKeys="true":返回自增主键
   keyProperty="id":类中的属性
   keyColumn="id":数据库中的列
-->
<mapper namespace="com.ffyc.mybatispro.dao.AdminDao">

                                                                   <!-- keyProperty:类中的属性keyColumn:数据库中的列-->
    <insert id="insertAdmin" parameterType="Admin" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
                              <!-- 数据库中的列名                      Admin对象中的属性-->
      insert into admin(account,password,gender) values (#{account},#{password},#{gender})
    </insert>


</mapper> 2、删除delete

   void deleteAdmin(int id);<?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">
<!--sql映射文件主要写sql实现-->
<!--
   useGeneratedKeys="true":返回自增主键
   keyProperty="id":类中的属性
   keyColumn="id":数据库中的列
-->
<mapper namespace="com.ffyc.mybatispro.dao.AdminDao">
         <delete id="deleteAdmin" parameterType="int">
    delete from
            admin where id =#{id}
         ​​​​​​​</delete>


</mapper> 3、修改update

   void updateAdmin(Admin admin);<?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">
<!--sql映射文件主要写sql实现-->
<!--
   useGeneratedKeys="true":返回自增主键
   keyProperty="id":类中的属性
   keyColumn="id":数据库中的列
-->
<mapper namespace="com.ffyc.mybatispro.dao.AdminDao">

         <update id="updateAdmin" parameterType="Admin">
      update admin set account=#{account},password=#{password} where id=#{id}
         </update>


</mapper> 4、查找select

   List<Admin> findAdmins(@Param("orderColumn")String account);<?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">
<!--sql映射文件主要写sql实现-->
<!--
   useGeneratedKeys="true":返回自增主键
   keyProperty="id":类中的属性
   keyColumn="id":数据库中的列
-->
<mapper namespace="com.ffyc.mybatispro.dao.AdminDao">

          <select id="findAdmins" resultType="Admin" parameterType="string">
         select * from admin order by ${orderColumn} desc
          </select>


</mapper> #{}和${}区别

#{ }:是占位符,是采用预编译方式向sql中传值,可以防止sql注入,如果我们往sql中传值,使用#{},更加安全。
${ }:是当作字符串将内容直接拼接到sql语句中,一样平常不用于向sql中传值(给列赋值),一样平常用于向sql中动态的传递列名。
   select * from table order by ${列名} desc
    1、底层实现不同

#{}:采用预编译方式,防止sql注入更加安全
${}:采用字符串拼接,直接将值拼接到sql中
2、使用场景不同

#{}:一样平常用于向sql 中的列传值
${}:一样平常用于向sql动态传递列名

例如:排序时 order by 后面的列名是可以改变。
例如:select 后面的列名也可以自由选择
单元测试

单元测试就是以方法为单位举行测试。
起首需要在maven项目标pom.xml文件中导入junit组件,然后在要测试的方法上添加@Test注解标签即可。
<!--junit-->
      <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>provided</scope>
      </dependency>
数据库事务

   1、简介

 数据库事务是数据库的一种管理的机制,是对一次链接数据库过程的管理。包管一次操纵中,执行的多条sql,要么都成功执行,要么都不执行。
提交事务,数据库才会真正的在数据库执行这一次操纵中的多条sql。
   当我们的程序代码执行没有任何问题时,再向数据库发送提交事务操作,数据库真正执行sql,出现异常则不提交事务。
<strong>新增,修改,删除完毕后,都需要手动提交事务。(查询不需要)</strong>public class Test3 {
    /*
      单元测试,程序员使用的测试方式,以方式为单位测试
      使用junit组件实现单元测试
   */

    //单元测试,以方法为单位,进行单元测试
    @Test
    public void insert(){
      Admin admin=new Admin();
      admin.setAccount("acc");
      admin.setPassword("125");
      admin.setGender("女");
      SqlSession sqlSession= MyBatisUtil.getSqlSession();
      AdminDao adminDao=sqlSession.getMapper(AdminDao.class);
               adminDao.insertAdmin(admin);//保存数据后,我们需要立刻拿到这条数据在数据库的主键
               sqlSession.commit();//提交数据库事务,当我们的程序代码执行没有任何问题时,再向数据库发送提交事务操作,数据库真正执行sql,出现异常则不提交事务
                                     // 新牌,修敌,删除完毕后,都需要手动提交事务。
               sqlSession.close();
   }

} 关联查询

1、直接多表关联査询出我们需要的数据

   Student findStudentById(int i);public class TestStudent {

    @Test
    public void test1(){
      SqlSession sqlSession= MyBatisUtil.getSqlSession();
      StudentDao studentDao=sqlSession.getMapper(StudentDao.class);
      Student student=studentDao.findStudentById(2);
      System.out.println(student.getId());
      System.out.println(student.getName());
      System.out.println(student.getMajor().getName());
      sqlSession.close();
    }
} <?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">
<!--sql映射文件主要写sql实现-->
<!--
   useGeneratedKeys="true":返回自增主键
   keyProperty="id":类中的属性
   keyColumn="id":数据库中的列
-->
<mapper namespace="com.ffyc.mybatispro.dao.StudentDao">


       <!--对关联查询到的学生信息进行自定义映射封装-->
    <resultMap id="studentMap" type="Student">
      <!--column是数据库property是属性-->
      <id column="id" property="id"></id>
      <result column="num" property="num"></result>
      <result column="name" property="name"></result>
      <result column="gender" property="gender"></result>
      <!--映射关联数据专业名称-->
      <!--映射关联数据 首先会创建一个Major对象,然后将专业名称封装到Major对象,最后将Major对象封装到Student对象中-->
      <association property="major" javaType="Major">
            <result column="mname" property="name"></result>
      </association>
    </resultMap>

      <!--关联查询方式1: 直接多表关联査询出我们需要的数据-->
    <select id="findStudentById" resultMap="studentMap">
         select
             s.id,
             s.num,
             s.name,
             s.gender,
             m.name mname
         from student s inner join major m on m.id=s.majorid where s.id=#{id}
    </select>

</mapper>
2、 嵌套查询,先查询主表(学生表)

   Student findStudentById1(int i);public class TestStudent {
@Test
    public void test3(){
      SqlSession sqlSession= MyBatisUtil.getSqlSession();
      StudentDao studentDao=sqlSession.getMapper(StudentDao.class);
      Student students=studentDao.findStudentById1(2);
      sqlSession.close();
    }
} <?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">
<!--sql映射文件主要写sql实现-->
<!--
   useGeneratedKeys="true":返回自增主键
   keyProperty="id":类中的属性
   keyColumn="id":数据库中的列
-->
<mapper namespace="com.ffyc.mybatispro.dao.StudentDao">
       关联查询方式2: 嵌套查询,先查询主表(学生表)-->
    <resultMap id="studentMap1" type="Student">
      <id column="id" property="id"></id>
      <result column="num" property="num"></result>
      <result column="name" property="name"></result>
      <result column="gender" property="gender"></result>
      <!--封装关联表数据-->
      <association property="major" javaType="Major" select="findMajorById" column="majorid"></association>
    </resultMap>

    <select id="findStudentById1" resultMap="studentMap1">
      select id,num,name,gender,majorid from student where id=#{id}
    </select>

    <!--嵌套查询学生关联的专业   resultType="Major"-->
    <select id="findMajorById" resultType="Major">
      select name from major where id=#{majorid}
    </select>

</mapper> 对象映射

如果表中的类名与类中的属性名完全类似,mybatis会主动将查询结果封装到POJO对象中。
如果java中使用尺度驼峰定名,数据库中使用下划线连接定名,可以开始全局设置实现主动转换。
查询单张表,主动将记录映射到对象中
多表关联查询  resultMap自定义映射。如图所示:
https://i-blog.csdnimg.cn/direct/c860672a31fe4d0a85ffadc558874edb.png
特殊符号处理

1、在 mybatis 中的 xml 文件,一些特殊符号需要转译:

特殊字符转译字符<&It;""'&apos;>>&&
2、使用 <!]>  

通过 <!]> 包裹特殊字符也可以
https://i-blog.csdnimg.cn/direct/c596f67edded42d99e142352b9db04e1.png

数据缓存

什么是缓存? 

缓存 (Cache):是一种用于临时存储数据的技能,将数据临时存储在内存中。
缓存的作用:让数据离我们的执行程序更近,让程序可以或许快速的获取到数据,减少对数据库的访问压力。
   缓存的主要范例有:
              CPU缓存:处理器内置的缓存,分为L1、L2和L3级别,存储经常使用的指令和数据,减少处理器访问主内存的时间。
              硬盘缓存:硬盘驱动器内部的缓存,暂存读写数据,以进步数据传输速度。
              Web缓存:在浏览器或代理服务器中缓存网页内容,以减少网络哀求次数,加快页面加载速度。
              数据库缓存:在数据库中使用缓存技能,存储查询结果,以加速数据库的响应时间。
➱ MyBatis 提供了一级缓存和二级缓存来进步数据库查询的性能。
1、mybatis一级缓存

       Mybatis对缓存提供支持,但是在没有配置的默认情况下,它只开启一级缓存,一级缓存只是相对于同一个SqlSession而言。
   <strong>有缓存,查询流程:</strong>
   先从缓存中查询数据,缓存中如果没有,去数据库査询,査询到后把数据放到缓存中,下次直接从缓存中获取.
<strong>mybatis一级缓存</strong>
       mybatis一级缓存,默认是SqlSession级别的,在同一个SqlSession中查询到数据先缓存到SqlSession对象中,第二次査询数据时,先从Sqlsession中查询,如果有直接返回。没有,再去查询数据库。
<strong>一级缓存生命周期: </strong>
                开始于SqlSession 创建
                结束于SqlSession关闭,如果期间执行了新增,修改,删除操作也会清空当前sqlSession对象中缓存数据(<strong>防止脏读</strong>)
                调用 sqlSession.clearCache():强制清空一级缓存数据一级缓存失效的情况:
   

[*]sqlSession.close();
[*]sqlSession.clearCache();
[*]SqlSession 中执行了任何一个修改操纵(update()、delete()、insert()) ,都会清空缓存的数据。


2、mybatis二级缓存

       二级缓存是SqlSessionFactory级别的,根据mapper的namespace划分区域的,类似namespace的mapper查询的数据缓存在同一个区域,如果使用mapper代理方法每个mapper的namespace都不同,此时可以理解为二级缓存区域是根据mapper划分。
   <strong>mybatis二级缓存</strong>
      二级缓存是SqlSessionFactory级别,可以让多个Sqlsession共享数据。
      mybatis默认没有开启二级缓存,使用时需要配置开启。

      如果开启了二级换成,当sqlsession关闭时,会将一级缓存中的数据,存储到二级缓存中.
      其他的sqlsession就可以二级缓存中查询到之前sqlsession查询的数据。
要开启二级缓存
需要举行以下步骤:

[*]在 MyBatis 全局配置文件中的<settings>标签中配置开启二级缓存,设置cacheEnabled为true(默认值就是true,也可以省略这一步)
[*]在具体的 mapper.xml 文件中添加<cache/>标签
[*]被缓存的 POJO(实体类)必须实现序列化接口(implements Serializable)
https://i-blog.csdnimg.cn/direct/8c4957720923467e8fccb0e9932e1629.png
https://i-blog.csdnimg.cn/direct/97dc6702538642aaa152d8c13481740d.png https://i-blog.csdnimg.cn/direct/4eea09e801fb4d78a8721d78cc049366.png
二级缓存的特点包括:



[*]mapper 映射文件中的全部 select 语句将会被缓存。
[*]mapper 映射文件中的全部 insert、update 和 delete 语句会刷新缓存。
[*]二级缓存是以 namespace 为单位的,不同 namespace 下的操纵互不影响。
[*]如果在加入<cache>标签的前提下让个别 select 元素不使用缓存,可以使用useCache属性,设置为false。
[*]缓存默认使用近来最少使用(LRU)算法来收回。
[*]根据时间表,如noFlushInterval(没有刷新隔断),缓存不会以任何时间顺序来刷新。
[*]缓存会存储列表聚集或对象(无论查询方法返回什么)的 1024 个引用。
[*]缓存会被视为是可读/可写(read/write)的缓存,意味着对象检索不是共享的,而且可以安全地被调用者修改,不干扰其他调用者或线程所做的潜伏修改。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 框架 +【Mybatis】概述 以及 基础环境搭建