ssm-mybatis

  • mybatis(简化数据库操作)—mybatis-plus

    • 结果集映射
    • 分页
    • 注解开发
    • 一对多,多对一-----难点
    • 动态sql
    • 缓存
      SpringBoot–动态web开发框架–简化ssm–太多的配置

本质一样

1.Mybatis

什么是Mybatis,有什么用
  • MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。
  • 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作
  • MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类 【Plain Old Java Objects,普通的 Java对象】映射成数据库中的记录。
  • Mybatis官方文档 : http://www.mybatis.org/mybatis-3/zh/index.html
  • GitHub : https://github.com/mybatis/mybatis-3

Mybati的优点

  • 简单易学
  • 提供xml配置
  • 解除sql与程序代码的耦合

什么是持久化

持久化是将程序数据在持久状态和瞬时状态间转换的机制。

  • 即把数据(如内存中的对象)保存到可永久保存的存储设备中(如磁盘)。持久化的主要应用是将内存中的对象存储在数据库中,或者存储在磁盘文件中、XML数据文件中等等
  • JDBC就是一种持久化机制。文件IO也是一种持久化机制。
  • 在生活中 : 将鲜肉冷藏,吃的时候再解冻的方法也是。将水果做成罐头的方法也是。

为什么需要持久化服务呢?那是由于内存本身的缺陷引起的

  • 内存断电后数据会丢失,但有一些对象是无论如何都不能丢失的,比如银行账号等,遗憾的是,人们还无法保证内存永不掉电。
  • 内存过于昂贵,与硬盘、光盘等外存相比,内存的价格要高2~3个数量级,而且维持成本也高,至少需要一直供电吧。所以即使对象不需要永久保存,也会因为内存的容量限制不能一直呆在内存中,需要持久化来缓存到外存。

持久层

  • 用来操作数据库
  • 将内存中的数据保存到磁盘上加以固化,而持久化的实现过程则大多通过各种关系数据库来完成。

如何使用

1.导入依赖
<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
    </dependency>
</dependencies>
引入资源
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>
2.从 XML 中构建 SqlSessionFactory,获取Sqlsession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //获取SqlSession连接
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }

}
3.xml文件
<?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">
        <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/jdbcstudy?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="Mapper.xml"/>
    </mappers>
</configuration>
4.创建Mapper接口以及xml配置文件
public interface Mapper {
    List<User> selectUser();
}
<?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="com.lcj.mybatis.mapper.Mapper">
    <select id="selectUser" resultType="com.lcj.mybatis.pojo.User">
  select * from mybatis
 </select>
</mapper>
5.测试
public void selectUser() {
    SqlSession session = MybatisUtils.getSession();
    Mapper mapper1 = session.getMapper(Mapper.class);
    List<User> users1 = mapper1.selectUser();
    //方法二:
    for (User user : users1) {
        System.out.println(user);
    }

    session.close();
}
6.与SpringBoot中使用对比
  • Springboot更简单

    • 导入依赖
    • 创建Mapper接口
    • 创建Mapper配置文件
    • yaml配置
  • 都是工具,帮助我们简单操作数据库

增删改查

增删改需要事务

练习

mapper接口
public interface Mapper {
    List<User> selectUser();
    //根据id查询用户
    User selectUserByName(String username);
    User selectUserByNP(Map<String,Object> map);
    int addUser(User user);
    int updateUser(User user);
    int deleteUser(String username);
}
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">
<mapper namespace="com.lcj.mybatis.mapper.Mapper">
 <select id="selectUser" resultType="com.lcj.mybatis.pojo.User">
  select * from mybatis
 </select>

 <select id="selectUserByName" resultType="com.lcj.mybatis.pojo.User">
  select * from mybatis where username = #{username}
 </select>
 <select id="selectUserByNP" resultType="com.lcj.mybatis.pojo.User" parameterType="map">
  select * from mybatis where username = #{username} and password = #{password}
 </select>
 <insert id="addUser" parameterType="com.lcj.mybatis.pojo.User">
    insert into mybatis (username,password,role,perms) values (#{username},#{password},#{role},#{perms})
</insert>
 <update id="updateUser" parameterType="com.lcj.mybatis.pojo.User">
  update mybatis set username=#{username},password=#{password} where role = #{role}
</update>
 <delete id="deleteUser" parameterType="String">
  delete from mybatis where username = #{username}
</delete>
</mapper>
测试
import com.lcj.mybatis.MybatisUtils;
import com.lcj.mybatis.mapper.Mapper;
import com.lcj.mybatis.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MybatisText {
    @Test
    public void selectUser() {
        SqlSession session = MybatisUtils.getSession();
        Mapper mapper1 = session.getMapper(Mapper.class);
        List<User> users1 = mapper1.selectUser();
        //方法二:
        for (User user : users1) {
            System.out.println(user);
        }
        User root = mapper1.selectUserByName("root");
        System.out.println(root.getPassword());
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("username","root");
        map.put("password","123456");
        User user = mapper1.selectUserByNP(map);
        System.out.println(user.getPerms());
        User user1 = new User("dtt1","123456","guest","user:view");
        int i = mapper1.addUser(user1);//创建事务
        System.out.println(i);
        User user2 = new User("lcj11","12345678","guest","user:view");
        int i1 = mapper1.updateUser(user2);
        System.out.println(i1);
        int lcj11 = mapper1.deleteUser("lcj11");
        System.out.println(lcj11);
        session.commit();//提交事务
        session.close();
    }
}
模糊查询

java代码的实现

List<User> users = mapper1.selectUserLike("%123%");
List<User> selectUserLike(String value);

 <select id="selectUserLike" resultType="com.lcj.mybatis.pojo.User">
  select * from mybatis where password like #{value}
 </select>

like(匹配)%

in(在)

小结
  • 传入多个参数可以设置Mapper中方法参数类型为map
  • 所有的增删改操作都需要事务!
    • 开启
    • 创建
    • 提交事务
  • @Param:可以指定参数的名字

配置解析

官方文档

https://mybatis.org/mybatis-3/zh/configuration.html

MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:

1.propoerties属性配置

引入外部配置文件–首先加载

自己设置属性

<properties resource="db.properties">
    <property name="name" value="root"/>
    <property name="pwd" value="123456"/>
</properties>

<environment id="text">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${name}"/>
                <property name="password" value="${pwd}"/>
            </dataSource>
</environment>
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8
2.Setting
cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true | falsetrue
lazyLoadingEnabled延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。true | falsefalse
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING未设置
3.类型别名(typeAliases)
  • 给我们的类取外号–简化开发

  • 扫描包

    <typeAliases>
        <typeAlias type="com.lcj.mybatis.pojo.User" alias="User"/>
        <!--<package name="com.lcj.mybatis.pojo"/>-->
        <!--使用包他会给我们的实体类对象取外号--小写,也可以自己用注解取外号-->
    </typeAliases>
    
  • Java 类型与mybtis中的映射

  • stringString
    mapMap
4.环境配置(environments)

可以配置多个环境,一个SqlSessionFactory一个配置文件–一个环境–一个数据库

事务管理器–jdbc

数据源–pooled

5.映射器(mappers)

指明我们的Mapper接口的配置文件在哪里

  • resource
  • class

Mybtis中对象的作用域和生命周期

SqlSessionFactoryBuilder

这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了

局部方法变量

SqlSessionFactory

SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例

数据库连接池–池--能产生很多连接

应用一创建就有

SqlSession

每个线程都应该有它自己的 SqlSession 实例。SqlSession的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域

连接到连接池的请求

用完应该关闭–连接池就可以释放资源

每个Mapper接口就相当于一个业务

ResultMap

resultMap 元素是 MyBatis 中最重要最强大的元素

<resultMap id="UserMapper" type="User">
  <result column="username" property="username"/>
  <result column="password" property="password"/>
  <result column="role" property="role"/>
  <result column="perms" property="perms"/>
</resultMap>
<select id="selectUser" resultMap="UserMapper">
 select * from mybatis
</select>

resultMap本质上也是实体类对象,只是他将数据库的列名与实体类对象属性对象,从而映射在实体类对象

日志

1.配置文件配置
<settings>
       <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
2.LOG4J
  • Log4j是Apache的一个开源项目
  • Log4j可以控制日志–使用配置文件
  • 代替sout
3.使用

1.导入依赖

<dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>1.2.17</version>
</dependency>

2.配置

#将等级为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/lcj.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

3.测试

  • 直接测试,打印我们想打印的日志–配置文件
  • 代替sout

分页

需求

  • 见小数据库的压力
  • 满足业务需求

实现

  • 使用MAP集合作为参数,将分页所需参数给sql语句
  • 使用插件

使用注解开发

关于接口的理解
  • 接口制定了规范与约束,我们去遵守—公司流程接口—各个部门对象
  • 个体–部门接口
  • 方面–Dao层–处理数据库
关于面向对象的理解
  • 面向对象,考虑问题时,万物皆对象,把任何物体都可以看作对象,考虑它的属性及方法 .
  • 面向过程,考虑问题时,关注他的过程,考虑它的实现 .

面向接口编程:MVC框架:Service,Dao层—Service直接调用dao层接口,不要取关心Dao层的具体实现

根本原因 : 解耦 , 可拓展 , 提高复用 , 分层开发中 , 上层不用管具体的实现 , 大家都遵守共同的标准 , 使得开发变得容易 , 规范性更好

注解开发

原理:利用反射的原理,获取类的全部信息(注解)–执行

1.创建Mapper接口

public interface UserMapper {
    @Select("select * from mybatis")
    List<User> selectUser();
}

2.核心配置文件–指明我们的Mapper接口

<mappers>
    <mapper resource="Mapper.xml"/>
    <mapper class="com.lcj.mybatis.mapper.UserMapper"/>
</mappers>

3.测试

@Test
public void annotion() {
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);
    List<User> users = mapper.selectUser();
    for (User user : users) {
        System.out.println(user.getUsername());
    }
}

执行流程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-w9czF7GB-1627961597583)(C:\Users\LCJ\AppData\Roaming\Typora\typora-user-images\image-20210730154303685.png)]

注解开发和配置文件开发搭配使用

高级查询-关联和集合

1.任何查询都要满足我们的需求

2.我们的需求是什么,我们想要得到什么数据(连表查询)

3.设计结果集映射

  • 直接根据数据做结果集映射

  • 一对多----集合

    • 实体类对象

      public class Teacher1 {
          int id;
          String name;
          List<Student1> student1s;
      }
      
      
    • 方式一:拼接sql

      • 这里传递过来的id,只有一个属性的时候,下面可以写任何值
        association中column多参数配置:
           column="{key=value,key=value}"
           其实就是键值对的形式,key是传给下个sql的取值名称,value是片段一中sql查询的字段名。
        
      <resultMap id="TeacherStudent2" type="Teacher1">
          <!--column是一对多的外键 , 写的是一的主键的列名  键值对传值(id:数据库的字段名)-->
          <collection property="student1s" javaType="ArrayList" ofType="Student1" column="id" select="getStudentByTeacherId"/>
      </resultMap>
      
      <select id="getStudentByTeacherId" resultType="Student1">
      select * from student where tid = #{id}
      </select>
      
      <!--查询所有的学生信息,1.通过ID获取老师信息,根据具老师ID获得学生信息-->
      <select id="getStudents1" resultMap="TeacherStudent2">
         select * from teacher where id = #{id}
      </select>
      
    • 方式二:结果映射–查所有

    • <select id="getStudents1" 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=#{id}
      </select>
      
       <resultMap id="TeacherStudent" type="Teacher1">
           <result  property="name" column="tname"/>
           <collection property="student1s" ofType="Student1">
               <result property="id" column="sid" />
               <result property="name" column="sname" />
               <result property="tid" column="tid" />
           </collection>
       </resultMap>
      
      
  • 多对一–关联

    • 结果映射–查所有

          <resultMap id="StudentTeacher2" type="Student">
              <id property="id" column="sid"/>
              <result property="name" column="sname"/>
              <!--关联对象property 关联对象在Student实体类中的属性-->
              <association property="teacher" javaType="Teacher">
                  <result property="name" column="tname"/>
              </association>
          </resultMap>
          <select id="getStudents2" 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="StudentMap" type="Student">
      	<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
      </resultMap>
      <select id="getStudents" resultMap="StudentMap">
          select * from student
      </select>
      
      <select id="getTeacher" resultType="Teacher">
         select * from teacher where id = #{id}
      </select>
      
  • 总结

    • JavaType和ofType都是用来指定对象类型的
      • JavaType是用来指定pojo中属性的类型
      • ofType指定的是映射到list集合属性中pojo的类型。

高级查询

数据库乱码解决:url=jdbc:mysql://localhost:3306/jdbcstudy?useSSL=false&useUnicode=true&characterEncoding=utf8

将& amp;替换成&

1.if,where—choose,when,overwise

需求:

  • 根据条件进行查询
    • 将我们的条件放入到map集合中
  • 方式一:if,where
<select id="queryBlogIf" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <!--if判断-->
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
</select>

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>
  • 方式二:choose,when,overwise–switch case,满足一个则跳出
<select id="queryBlogChoose" parameterType="map" resultType="blog">
    select * from 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>
2.Set

需求:根据条件修改数据

<update id="updateBlog" parameterType="map">
    update blog
    <set>
        <if test="title != null">
            title = #{title},
        </if>
        <if test="author != null">
            author = #{author}
        </if>
    </set>
    where id = #{id};
</update>

这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

3.foreach

需求:对集合进行遍历(尤其是在构建 IN 条件语句的时候)

<select id="queryBlogForeach" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <!--
        collection:指定输入对象中的集合属性,需传入一个集合(有名字的)
        item:每次遍历生成的对象
        open:开始遍历时的拼接字符串
        close:结束时拼接的字符串
        separator:遍历对象之间需要拼接的字符串
        select * from blog where 1=1 and (id=1 or id=2 or id=3)
      -->
        <foreach collection="ids"  item="id" open="id in (" close=")" separator=",">
            #{id}
        </foreach>
    </where>
</select>
4.SQL片段

有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。

提取SQL片段:

<sql id="if-title-author">
   <if test="title != null">
      title = #{title}
   </if>
   <if test="author != null">
      and author = #{author}
   </if>
</sql>

引用SQL片段:

<select id="queryBlogIf" parameterType="map" resultType="blog">
  select * from blog
   <where>
       <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
       <include refid="if-title-author"></include>
       <!-- 在这里还可以引用其他的 sql 片段 -->
   </where>
</select>

注意:

①、最好基于 单表来定义 sql 片段,提高片段的可重用性

②、在 sql 片段中不要包括 where

缓存

为什么要使用缓存?

减少与数据库的交互,减少系统开销,提高系统效率

什么是缓存?
  • 存在内存中的临时数据。
  • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
Mybatis中提供的缓存
1.一级缓存–本地缓存
  • 一次会话–与数据库建立的一次连接(Sqlsession)

  • 与数据库同一次会话(与数据库建立的连接)期间查询到的数据会放在本地缓存中。

2.二级缓存
  • 全局缓存,作用域高

  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;

  • 我们与数据库建立会话,查询到的数据就会放在一级缓存中,当这次连接关闭或提交,数据就从一级缓存放入二级缓存(一个Mapper接口就对应一个二级缓存,放在自己对应的Mapper缓存里)

  • 新的会话就可以直接从二级缓存中取数据

  • 总结:只要开启了二级缓存,我们在同一个Mapper中的查询,可以在二级缓存中拿到数据

  • 作用时间:程序开始–结束

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值