Mybatis框架基础知识

Mybatis

1.1什么是Mybatis

1.MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。

2.MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。

3.MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

1.2持久化

数据持久化

  • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程

  • 内存:断电即失

  • 数据库(jjdbc),io文件持久化

  • 生活:冷藏,罐头

为什么需要持久化?

  • 有一些对象,不能让他丢掉

  • 内存太贵了

1.3持久层

Dao层,Service层,Controller层

  • 完成持久化工作的代码块

  • 层界限十分明显

1.4为什么需要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,'王五','023456')

新建项目

1.创建一个普通的maven项目

2.删除src目录

3.导入依赖

    
<!--导入依赖-->
    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

2.2创建一个模块

  • 编写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>核心配置文件-->
    <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="123456"/>
                </dataSource>
            </environment>
        </environments>
    ​
    </configuration>

  • 编写mybatis工具类

     
//从 SqlSessionFactory 中获取 SqlSession
//使用mybatis第一步:获取SqlSessionFactory对象
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) {
            throw new RuntimeException(e);
        }
    }
    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
    public static SqlSession  getSqlSession(){
        return sqlSessionFactory.openSession();
​
    }
}
2.3编写

代码

  • 实体类

//实体类
public class User {
    private int id;
    private String name;
    private String pwd;
​
    public User() {
    }
​
    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
​
    public int getId() {
        return id;
    }
​
    public void setId(int id) {
        this.id = id;
    }
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public String getPwd() {
        return pwd;
    }
​
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
​
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}
  • 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.nan.dao.UserDao">
    <select id="getUserlist" resultType="com.nan.pojo.User">
        select * from mybatis.user
    </select>
</mapper>

2.4测试

public class UserDaoTest {
    @Test
    public void test(){
        //1.获取sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
​
            //2.执行sql 方式一:getMapper
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            //这里.class是反射,可以获取本项目中的任意一个实体类的对象
            List<User> userlist = userDao.getUserlist();
            for (User user : userlist) {
                System.out.println(user);
            }
        }catch (Exception e){
              e.printStackTrace();
        }finally {
            //关闭sqlSession
            sqlSession.close();
        }
​
​
//手动抛出异常,建议这样写,把资源关闭写在finally
​
​
    }
}

3.CRUD

1.namespace

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

2.select

选择,查询语句

  • id:就是对应的namespace中的方法名

  • resultType:Sql语句执行的返回值

  • parameterType:参数类型

    1.编写接口

    //根据id查询用户
    User getUserById(int id);

    2.编写对应的mapper中的sql语句

    <select id="getUserById" parameterType="int" resultType="com.nan.pojo.User">
        select *from mybatis.user where id = #{id}
    </select>

    3.测试

    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userById = mapper.getUserById(1);
        System.out.println(userById);
        
        sqlSession.close();
    }

3.Insert

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

4.update

<update id="updateUser" parameterType="com.nan.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>

注意点:增删改需要提交事务

接口

public interface UserMapper {
    //查询全部用户
    List<User> getUserlist();
    //根据id查询用户
    User getUserById(int id);
    //insert一个用户
    //增加一个用户
    int addUser(User user);
    //修改用户
    int updateUser(User user);
    //删除用户
    int deleteUser(int id);
}

xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace 绑定对应的Dao接口/Mapper接口-->
<mapper namespace="com.nan.dao.UserMapper">
    <select id="getUserlist" resultType="com.nan.pojo.User">
        select *from mybatis.user
    </select>
    <select id="getUserById" parameterType="int" resultType="com.nan.pojo.User">
        select *from mybatis.user where id = #{id}
    </select>
    <insert id="addUser" parameterType="com.nan.pojo.User">
        insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>
    <update id="updateUser" parameterType="com.nan.pojo.User">
        update mybatis.user set name = #{name}, pwd=#{pwd} where id=#{id};
    </update>
    <delete id="deleteUser" parameterType="int">
        delete from  mybatis.user where id=#{id};
    </delete>
</mapper>

测试

@Test
public void getUserById(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User userById = mapper.getUserById(1);
    System.out.println(userById);
​
    sqlSession.close();
}
@Test
public void addUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    mapper.addUser(new User(4,"哈哈","123333"));
    //提交事务 不提交的话插入不成功
    sqlSession.commit();
    sqlSession.close();
}
@Test
public void updateUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    mapper.updateUser(new User(4,"呵呵","123123"));
    sqlSession.commit();
    sqlSession.close();
}

@Test
public void deleteUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    mapper.deleteUser(4);
    sqlSession.commit();
    sqlSession.close();
}

6.万能Map

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

//万能的Map
int addUser2(Map<String,Object> map);
<insert id="addUser2" parameterType="map">
    insert into mybatis.user(id,name,pwd) values (#{userid},#{username},#{userpwd})
</insert>
   @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("usernme","hello");
        map.put("userpwd","222333");
​
        mapper.addUser2(map);
        //提交事务 不提交的话插入不成功
        sqlSession.commit();
        sqlSession.close();
    }
}

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

对象传递参数,直接在sql中取对象的属性即可

parameterType="int"

只有一个基本类型参数的情况下,可以直接在sql中取到

多个参数用Map,或者注解!

7.模糊查询怎么写

  1. java代码执行的时候,传递通配符% %

List<User> userList = mapper.getUserLike("%李%");
for (User user : userList) {
    System.out.println(user);
}
  1. 在sql拼接中使用通配符


<select id="getUserLike" resultType="com.nan.pojo.User" >
    select *from mybatis.user where name like "%"#{value}"%"
</select>
 

4.配置解析

4.1核心配置文件

  • mybatis-config.xml

  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。

  • configuration(配置)
    properties(属性)
    settings(设置)
    typeAliases(类型别名)
    typeHandlers(类型处理器)
    objectFactory(对象工厂)
    plugins(插件)
    environments(环境配置)
    environment(环境变量)
    transactionManager(事务管理器)
    dataSource(数据源)
    databaseIdProvider(数据库厂商标识)
    mappers(映射器)

4.2属性配置

编写一个配置文件 db.properties

driver = com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456

在核心配置文件中引入

<!-- 引入外部配置文件 -->
    <properties resource="db.properties">
    </properties>

如果有两个文件有同一个字段,优先使用外部配置文件的

4.3类型别名(typeAliases)

类型别名可为 Java 类型设置一个缩写名字。

它仅用于 XML 配置,意在降低冗余的全限定类名书写。

1.起别名

  <typeAliases>
<typeAlias type="com.nan.pojo.User" alias="User"/>
   </typeAliases>

2.根据包名

<!--  可以给实体类起别名  -->
    <typeAliases>
 <package name="com.nan.pojo"/>
    </typeAliases>

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,扫描实体类的包,它的默认别名就是这个类的类名,首字母小写

实体类少,使用第一种,可以diy

实体类多,就用第二种

可以在实体类上增加注解

@Alias("user")

4.4环境配置

1.尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

2.如果你想连接两个数据库,就需要创建两个 SqlSessionFactory 实例,每个数据库对应一个。而如果是三个数据库,就需要三个实例

3.注意一些关键点:

  • 默认使用的环境 ID(比如:default="development")。

  • 每个 environment 元素定义的环境 ID(比如:id="development")。

  • 事务管理器的配置(比如:type="JDBC")。

  • 数据源的配置(比如:type="POOLED")。

4.在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]")

4.5设置(settings)

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

设置名描述有效值默认值
cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true | falsetrue
lazyLoadingEnabled延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。true | falsefalse
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J | LOG4J(3.5.9 起废弃) | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING未设置

4.6映射器(mappers)

方式一: 资源路径

  <mappers>
<mapper resource="com/nan/dao/UserMapper.xml"></mapper>
   </mappers>

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

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

注意点:

1.接口和它的Mapper配置文件必须同名

2.接口和它的Mapper配置文件必须在同一个包下

方式三:通过扫描实体类的包去绑定

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

注意点:

1.接口和它的Mapper配置文件必须同名

2.接口和它的Mapper配置文件必须在同一个包下

4.7作用域(Scope)和生命周期

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

SqlSessionFactoryBuilder

一旦创建了 SqlSessionFactory,就不再需要它了,最佳作用域是方法作用域(也就是局部方法变量)

SqlSessionFactory

1.说白了,可以想象为数据库连接池

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

3.SqlSessionFactory 的最佳作用域是应用作用域。

4.最简单的就是使用单例模式或者静态单例模式。

SqlSession

1.每个线程都应该有它自己的 SqlSession 实例。

2.可以理解为连接到连接池的一个请求,需要开启和关闭

3.作用域是请求或方法作用域。

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

String pwd  数据库的字段名
String password  实体类的属性名    

1.起别名

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

2.结果集映射

<!--  结果集映射-->
    <resultMap id="UserMap" type="User">
<!--column写数据库中的字段名 property写实体类的属性名-->
        <result column="id" property="id"></result>
        <result column="name" property="name"></result>
        <result column="pwd" property="password"></result>
    </resultMap>
    
    <select id="getUserById" parameterType="int" resultMap="UserMap">
        select *from mybatis.user where id = #{id}
    </select>

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

2.你会发现上面的例子没有一个需要显式配置 ResultMap,这就是 ResultMap 的优秀之处——你完全可以不用显式地配置它们。

3.你的程序更可能会使用 JavaBean 或 POJO(Plain Old Java Objects,普通老式 Java 对象)作为领域模型。

4.如果这个世界总是这么简单就好了。

6.日志

6.1日志工厂

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

以前:sout debug

现在:日志工厂

logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。

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.2LOG4J

1.Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件

2.我们也可以控制每一条日志的[输出格式]

3.通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。

4.最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

1.先导入LOG4J的包

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

2.写配置文件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

3.在xml里面setting它

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

4.log4j的简单使用

  • 在使用LOG4J的类中,导入包import org.apache.log4j.Logger

  • 日志对象,参数为当前类的class

public class UserDaoTest {
    static  Logger logger = Logger.getLogger(UserDaoTest.class);
    @Test
    public void testlog4j(){
        
    }
}
  • 日志级别

public void testlog4j(){
  logger.info("info:进入了log4j");
  logger.debug("debug:进入了log4j");
  logger.error("error:进入了log4j");
​
}

7.分页

为什么要分页?

  • 减少数据的处理量

7.1使用Limit分页

select *from mybatis.user limit 3
3个数据为一页
​
select *from mybatis.user limit 0,2
从第0个数据开始,每2个为一页

使用Mybatis实现分页,核心Sql

1.接口

List<User> getUserByLimit(Map<String,Integer>map);

2.Mapper.xml

<!--  分页  -->
    <select id="getUserByLimit" parameterType="map" resultType="User">
        select *from mybatis.user limit #{startindex},#{pagesize}
    </select>

3.测试

public class UserDaoTest {
    static  Logger logger = Logger.getLogger(UserDaoTest.class);
    @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> userByLimit = mapper.getUserByLimit(map);
        for (User user : userByLimit) {
            System.out.println(user);
        }
        sqlSession.close();
    }

7.2RowBounds分页

7.3分页插件

mybatis插件pagehelper

8.使用注解开发

8.1面向接口编程

什么是面向接口编程

面向接口编程就是先把客户的业务逻辑线提取出来,作为接口,业务具体实现通过该接口的实现类来完成。 当客户需求变化时,只需编写该业务逻辑的新的实现类,通过更改配置文件(例如Spring框架)中该接口 的实现类就可以完成需求,不需要改写现有代码,减少对系统的影响。

所有的定义与实现分离

1.关于接口的理解。

接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。

接口的本身反映了系统设计人员对系统的抽象理解。

接口应有两类:第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);

第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);

一个体有可能有多个抽象面。

抽象体与抽象面是有区别的。

面向接口编程的优点
  1. 降低程序的耦合性

  2. 易于程序的扩展

  3. 有利于程序的维护

8.2使用注解开发

解耦

1.注解在接口上实现

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

2.需要在核心配置文件中绑定接口

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

3.测试

public class UserMapperTest {
    @Test
​
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //底层实现主要通过反射
        List<User> users = mapper.getUsers();
        for (User user : users) {
            System.out.println(user);
        }
​
        sqlSession.close();
    }
}

本质:反射机制实现

底层:动态代理

mybatis详细执行流程

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

public static SqlSession  getSqlSession(){
    return sqlSessionFactory.openSession(true);
​
}

8.3@Param()注解

1.基本类型的参数或者String类型,需要加上

2.引用类型不需要加

3.如果只有一个基本类型的话,就可以忽略

4.我们在sql语句中引用的就是这里的@Param("id")中设定的属性名

#{} ${}区别

1.#{} 能防止sql注入

#{}作为sql的参数占位符,Mybatis会将sql中的#{}替换为?号,在sql执行前会使用PrepareStatement的参数设置方法,按序给sql的?号占位符设置参数值。

2.${} 不能防止sql注入

9.Lombok

使用步骤

1.在idea中下载lombok插件

2.在项目中导入maven依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.30</version>
</dependency>

3.在实体类中加注解

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
    
}
​
​
​
@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
    
 常用:   
@Data:  无参构造,get set toString hashcode  equals
@NoArgsConstructor  无参构造
@AllArgsConstructor  有参构造
@EqualsAndHashCode
@ToString   
@Getter and @Setter

10.多对一处理

多个学生对应一个老师

  • 对于学生这边而言,关联多个学生,关联一个老师(多对一)

  • 对于老师而言,集合,一个老师有很多学生(一对多)

10.1按照查询嵌套处理

    <select id="getStudent" resultMap="StudentTeacher">
        select * from student
    </select>
    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id"></result>
        <result property="name" column="name"></result>
<!--    复杂的属性,我们需要单独处理, 对象:association 集合:collection    -->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
    </resultMap>
    <select id="getTeacher" resultType="Teacher">
        select *from teacher where id=#{id}
    </select>

10.2按照结果嵌套处理

<!--  按照结果嵌套处理  -->
    <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>
        <result property="name" column="sname"></result>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"></result>
        </association>
    </resultMap>

11.一对多处理

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

环境搭建和刚才一样

实体类

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

11.1结果嵌套查询

  <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>
        <result property="name" column="tname"></result>
<!--     集合中的泛型信息,我们用ofType获取   -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"></result>
            <result property="name" column="sname"></result>
            <result property="tid" column="tid"></result>
        </collection>
    </resultMap>

11.2按照子查询

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

小结:

association关联 多对一

collection 集合 一对多

javaType 用来指定实体类中属性的类型

ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型

注意点:

  • 保证SQL的可读性,尽量保证通俗易懂

  • 注意属性名和字段的问题

  • 如果问题不好排错,可以使用日志,log4j

面试高频:

  • Mysql引擎

  • InnoDB底层原理

  • 索引

  • 索引优化

12.动态 SQL

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

动态SQL就是根据根据不同条件生成不同的sql语句

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

建议:

先在Mysql中写出完整的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.编写实体类

@Data
public class Blog {
    private  String id;
    private  String title;
    private  String author;
    private Date createTime;
    private int views;
}

4.编写实体类对应Mapper接口和Mapper.xml文件

public interface BlogMapper {
    int addBlog(Blog blog);
}
<?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">
<mapper namespace="com.nan.dao.BlogMapper">
    <insert id="addBlog" parameterType="blog">
        insert into blog(id,title,author,create_time,views)
        values (#{id},#{title},#{author},#{createTime},#{views});
    </insert>
</mapper>

12.1IF

xml

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

测试

@Test
public void  Mytest1(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    List<Blog> blogs = mapper.queryBlogIF(map);
​
    map.put("title","java");
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    mapper.queryBlogIF(map);
    sqlSession.close();
}

12.2choose、when、otherwise

<!--  id就是接口里面写的方法 返回类型就写泛型里面的 参数看自己写的啥 -->
    <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>

trim、where、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就是把逗号去掉

12.3SQL片段

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

1.使用SQL标签抽取公共的部分

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

2.在需要使用的地方使用include标签引用即可!

<select id="queryBlogIF" parameterType="map" resultType="Blog">
    select *from blog
 <where>
     <include refid="if-title-author"></include>
 </where>
</select>

注意事项:

  • 最好基于单表来定义SQL片段

  • 不要存在where标签

12.4Foreach

接口

//查询1.2.3号记录的博客
List<Blog> queryBlogForeach(Map map);

xml

<select id="queryBlogForeach" parameterType="map" resultType="Blog">
    select *from blog
    <where>
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id=#{id}
        </foreach>
    </where>
</select>

测试

   public void MyForeach(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        ArrayList<Integer> ids = new ArrayList<>();
        ids.add(1);
        map.put("ids",ids);
        List<Blog> blogs = mapper.queryBlogForeach(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }
}

13.缓存

查询: 连接数据库,耗资源
    一次查询的结果,给他暂存在一个可以直接取到的地方-->内存:缓存
我们再次查询相同数据的时候,直接走缓存,就不用走数据库了
    

一.什么是缓存?

首先我们要知道缓存其实就是一个临时的存储器。 缓存有 :cookie、session、application、cache、redis

二.作用

缓存主要是为了提高数据的读取速度。因为服务器和应用客户端之间存在着流量的瓶颈,所以读取大容量数据时,使用缓存来直接为客户端服务,可以减少客户端与服务器端的数据交互,从而大大提高程序的性能。

三.介绍缓存

1.硬件的缓存? cpu缓存:位于cpu和内存之间的临时存储器 2.软件缓存? 软件缓存分为三级 内存缓存(预先将数据写到容器(list,map,set)等数据存储单元中, 就是软件内存缓存) 数据库缓存 网络缓存 3.内存缓存淘汰机制分为三种 FIFO(First In,First Out)先进先出 优点:是先进先出的数据缓存器,他与普通存储器的区别是没有外部 读写地址线,这样使用起来非常简单。 缺点:只能顺序写入数据,顺序的读出数据,其数据地址由内部读写指针自动加1完成,不能像普通存储器那样可以由地址线决定读取或写入某个指定的地址 LFU(Least Freauently Used) 最不经常使用页置换算法,清理掉留给经常使用的使用 LRU(Least Recently Used)喜新厌旧 内存管理的一种页面置换算法,新加入的数据放到链表的头部,当缓存命中(被访问)数据移到链表的头部,当链表满的时候,将链表尾部的数据丢弃。

13.1一级缓存

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

一级缓存其实就是 SqlSession 级别的缓存

测试步骤:

开启日志

测试在一个Session中查询两次相同记录

   public  void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.queryUserById(1);
        System.out.println(user);
        System.out.println("---------------------------------------");
        User user2 = mapper.queryUserById(1);
        System.out.println(user2);
        sqlSession.close();
    }
}

查看日志输出

Opening JDBC Connection
Created connection 1151593579.
==>  Preparing: select *from user where id=?
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 张三, 123456
<==      Total: 1
User(id=1, name=张三, pwd=123456)
---------------------------------------
User(id=1, name=张三, pwd=123456)
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@44a3ec6b]
Returned connection 1151593579 to pool.
​

缓存失效的情况:

  1. 查询不同的东西

  2. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存

  3. 查询不同的Mapper.xml

  4. 手动清理缓存

  5. sqlSession.clearCache();//手动清理缓存

13.2二级缓存

多个 SqlSession 需要共享缓存,则需要开启二级缓存,要在同一个namespace级别

只要开启了二级缓存,在同一个Mapper下就有效

所有的数据都会先放在一级缓存中,只有当会话提交,或者关闭的时候,才会提交到二级缓存中

设置 cache 标签的属性

cache 标签有多个属性,一起来看一些这些属性分别代表什么意义

  • eviction

    : 缓存回收策略,有这几种回收策略

    • LRU - 最近最少回收,移除最长时间不被使用的对象

    • FIFO - 先进先出,按照缓存进入的顺序来移除它们

    • SOFT - 软引用,移除基于垃圾回收器状态和软引用规则的对象

    • WEAK - 弱引用,更积极的移除基于垃圾收集器和弱引用规则的对象

步骤:

1.开启全局缓存

在mybatis-config.xml核心配置文件中

<!--    显示开启全局缓存    -->
        <setting name="cacheEnabled" value="true"/>

2.在要使用二级缓存的Mapper中开启

<!--  在当前的Mapper.xml中使用二级缓存  -->
    <cache></cache>

也可以自定义一些参数

<!--  在当前的Mapper.xml中使用二级缓存  -->
    <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true">
    </cache>

3.测试

我们需要将实体类序列化!

​
public Class User implements Serializable {}

13.3缓存原理

缓存顺序:

1.先看二级缓存中有没有

2.再看一级缓存中有没有

3.查询数据库

13.4自定义缓存 ehcache

主要面向通用缓存

要在程序中使用ehcache,需要导包

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

编写配置文件

<?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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值