狂神说Java个人笔记-Mybatis

Mybatis

image-20200627131702364

1.创建第一个Mybatis

1.1搭建环境

  1. 创建SQL表格


    CREATE TABLE `mybatis`.`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,'李四','123123'),
    (3,'王五','456456')

     

  2. 创建一个maven项目,删除src

  3. 配置maven依赖

<!--导入依赖-->
   <dependencies>
<!--       mysql驱动-->
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.47</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>
   </dependencies>

1.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>
   <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=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
               <property name="username" value="root"/>
               <property name="password" value="19941027"/>
           </dataSource>
       </environment>
   </environments>
   <mappers>
       <mapper resource="org/mybatis/example/BlogMapper.xml"/>
   </mappers>
</configuration>
  • 编写mybatis工具类

//sqlSessionFactory -->sqlSession
public class MybatisUtils {
   private static SqlSessionFactory sqlSessionFactory;
   static{
       //使用Mybatis第一步:获取SqlSessionFactory对象

       try {
           String resource="mybatis-config.xml";
           InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
      } catch (IOException e) {
           e.printStackTrace();
      }
  }
   //既然有了SqlSFactory,顾名思议,我们就可以从中获得SqlSession的实例了。
   //SqlSession 完全包含了面向数据库执行SQL命令所需要的方法。
   public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
  }
}

1.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 UserMapper {
   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">
<mapper namespace="com.dong.dao.UserMapper">
   <select id="getUserList" resultType="com.dong.pojo.User">
      select * from mybatis.user;
 </select>
</mapper>

2.4测试

  • Junit测试

image-20200627153040815

public class UserMapperTest {
   @Test
   public void test(){
       //获取SqlSession
       SqlSession sqlSession = MybatisUtils.getSqlSession();
       UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       List<User> userList = mapper.getUserList();
       for (User user : userList) {
           System.out.println(user);
      }
  }
}

步骤总结:

  1. maven

  2. 创建工具类

  3. 配置文件

  4. 实体类

  5. 接口

  6. 接口实现配置文件

  7. 测试

注意点:程序运行时可能找不到配置文件,所以需要在pom。xml文件里添加如下代码。

 <!--防止程序在运行时没有找到xml或者properties文件,让它们在src/main/java文件下也寻找相关文件 -->
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
        </resource>

        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
        </resource>
    </resources>
</build>

可能遇到的问题:

  1. 配置文件没有注册。

  2. 绑定接口错误。

  3. 方法名不对

  4. 返回类型不对

  5. Maven导出资源问题

  6. JDBC信息填写错误问题

3.CRUD

1.namespace命名空间

namespace中的包名要和mapper接口的包名保持一致

2.select

选择,查询语句

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

  • resultType:Sql语句的返回值!

  • parameterType:参数类型

image-20200629152345885

3.增删改

<?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命名空间-->
<mapper namespace="com.dong.dao.UserMapper">
<!--   id:方法名
 返回类型:返回值的类型-->
    <select id="getUserList" resultType="com.dong.pojo.User">
    select * from user
  </select>
    <select id="findUserById" parameterType="int" resultType="com.dong.pojo.User">
        select * from user where id=#{id}
    </select>
    <insert id="addUser" parameterType="com.dong.pojo.User">
        insert into user(id,name,pwd)values (#{id},#{name},#{pwd});
    </insert>
    <delete id="deleteUserById" parameterType="int">
        delete from user where id=#{id}
    </delete>
    <update id="updateUserById" parameterType="com.dong.pojo.User">
        update user set name=#{name},pwd=#{pwd} where id=#{id} ;
    </update> 

接口:

public interface UserMapper {
    //1.获取用户信息
    List<User> getUserList();

    //2.获取一个用户信息
    User findUserById(int id);

    //3.添加一个用户
    void addUser(User user);
    //4.删除一个用户
    void deleteUserById(int id);
    //5.修改用户
    void updateUserById(User user);
}

测试:

public class UserMapperTest {
    @Test
    public void test(){
        //第一步:获取SQLSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //执行sql
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.getUserList();
        for (User user : users) {
            System.out.println(user);
        }
        sqlSession.close();
    }

    @Test
    public void findUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.findUserById(1);
        System.out.println(user);
        sqlSession.close();
    }
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.addUser(new User(4,"赵乐观","666666"));
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void deleteUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUserById(4);
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void updateUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUserById(new User(3,"赵开心","888888"));
        sqlSession.commit();
        sqlSession.close();
    }
}

 

注意点:

  • 增删改需要提交事务!

image-20200629154953492

4.万能map

sql:

<select id="findUserById2" parameterType="map" resultType="com.dong.pojo.User">
    select * from user where id=#{helloId} and name=#{name};
</select>

接口:

User findUserById2(Map<String,Object> map);

测试:

@Test
public void findUserById2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("helloId",1);
    map.put("name","赵东");
    User user = mapper.findUserById2(map);
    System.out.println(user);
    sqlSession.close();
}

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

对象传递参数,直接在SQL中取对象的属性即可![parameterType="Object"]

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

多个参数用map、或注解

5思考题

模糊查询怎么写?

List<User> getUserLike(String value);
<select id="getUserLike" resultType="com.dong.pojo.User">
    select * from user where name like #{value};
</select>
public void getUserLike(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> userLike = mapper.getUserLike("%赵%");
    for (User user : userLike) {
        System.out.println(user);
    }
    sqlSession.close();
}

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

List<User> userLike = mapper.getUserLike("%赵%");

2.在SQL拼接中使用通配符!

select * from user where name like "%"#{value}"%"

5.配置

1.核心文件配置mybatis-config.xml

 

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

2.环境配置

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

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

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

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

3.属性(properties)

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

这些属性都是可外部配置且可动态替换的,既可以在典型的java属性文件中配置,亦可通过properties元素的子元素来传递。【db.properties】

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

在核心配置文件中映入

<!--    引入外部配置文件-->
    <properties resource="db.properties">
<!--        -->
        <property name="username" value="root"/>
        <property name="password" value="19941027"/>
    </properties>
  • 可以直接引入外部文件

  • 可以在其中增加一些属性配置

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

<configuration>
<!--    引入外部配置文件-->
    <properties resource="db.properties">
<!--        -->
        <property name="username" value="root"/>
        <property name="password" value="19941027"/>
    </properties>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/dong/dao/UserMapper.xml"/>
    </mappers>
</configuration>

4.类型别名(typeAliases)

  • 类型别名是为java类型设置一个短的名字。

  • 存在的意义仅在于用来减少类完全限定名的冗余。

<!--    可以给实体类起别名-->
    <typeAliases>
        <typeAlias type="com.dong.pojo.User" alias="User"/>

    </typeAliases>

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

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

在实体类比较少的时候,使用第一种方式。

如果实体类十分多,建议使用第二种,

第一种可以DIY(自定义)别名,第二种是默认的。

另一种可以给实体类加上注解,(优先级更高)

    @Alias("user")
public class User {}

5.设置

image-20200729170957604

6.其它配置

 

7.映射器(mappers)

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

image-20200729171639998

方式1:

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

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

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

注意点:

  • 接口和他的Mapper配置文件必须同名!

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

方式3:

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

注意点:

  • 接口和他的Mapper配置文件必须同名!

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

8.生命周期

image-20200729173614943

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

SQLSessionFactoryBuilder:

  • 一旦创建了SQLSessionFactory,就不再需要它了

  • 局部变量

SqlSessionFactory:

  • 说白了就是可以以想象为:数据库连接池

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

  • 因此SqlSessionFactory的最佳作用域是应用作用域。

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

SqlSession

  • 连接到连接池的一个请求!

  • SqlSession的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。

  • 用完之后需要赶紧关闭,否则资源被占用!

image-20200729174633457

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

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

1.问题

image-20200729180703947

假如属性pwd在实体类写为password

最后查询结果会为null

image-20200729180851679

2.resultMap

结果集映射

  <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="getUserList" resultMap="UserMap">
    select * from user
  </select>
  • resultMap元素是MyBatis中最重要最强大的元素

  • ResultMap的设计思想是,对于简单的语句根本不需要配置显式的结果影射,而对于复杂的语句只需要描述它们的关系就行了。

  • ResultMap最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们

  • 如果世界总是这么简单就好了。

6.日志

6.1日志工厂

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

曾经: sout debug

image-20200730090908300

  • SLF4J

  • LOG4J 【掌握】

  • LOG4J2

  • JDK_LOGGING

  • COMMONS_LOGGING

  • STDOUT_LOGGING 【掌握】

  • NO_LOGGING

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

STDOUT_LOGGING

    <settings>
<!--标准的日志工厂实现-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

6.2Log4j

什么是Log4j?

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

  • 我们也可以控制每一条日志的输出格式;

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

  • 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

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/dong.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.配置log4j为日志的实现

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

4.Log4j的使用!,直接测试运行刚才的查询

image-20200730102325515

简单使用

1.在要使用log4j的类中,导入包 import org.apache.log4j.Logger;

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

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

3.日志级别

logger.info("info:进入了testLog4j");
logger.debug("debug:进入了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.接口

2.Mapper.XML

3.测试

public void getUserByLimit(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    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.2RowBounds分页

7.3分页插件

image-20200730145213241

8.使用注解开发

8.1面向接口编程

-大家之前都学过面向对象编程,也学习过接口,但在真正开发中,很多时候我们会选择面向接口编程

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

-在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的,在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;

-而各个对象之间的协作关系则成为系统设计的关键。小道不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。

关于接口的理解

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

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

-接口应有两类:

-第一类是对一个个体的抽象,它可对应为一个抽象提(abstract class);

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

-一个体有可能有多个抽象面。抽象体与抽象面是由区别的。

三个面向区别

  • 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法

  • 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现

  • 接口设计与非接口设计师针对复用技术而言,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构

8.2使用注解开发

1.注解在接口上实现

//3.使用注解
@Select("select * from user")
List<User> getUsers();

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

  <mappers>
        <mapper resource="com/dong/dao/UserMapper.xml"/>
<!--        <mapper class="com.dong.dao.UserMapper"/>-->
    </mappers>

3.测试

@Test
public void getUsers(){
    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详细执行流程

8.3使用注解CRUD

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

//方法存在多个参数,参数前必须加上@Param("id")注解
@Select("select *from user where id=#{id}")
User findUserById(@Param("id") int id);
public void getUsers(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User userById = mapper.findUserById(2);
    System.out.println(userById);
    sqlSession.close();
}

 

测试类

【注意:我们必须要将接口注册绑定到我们的核心配置文件中!】

关于@Param()注解

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

  • 引用类型不需要加

  • 如果只有一个基本类型的话,可以忽略,但是建议大家都加上!

  • 我们在SQL中引用的就是我们这里的@Param(“uid”)中设定的属性名!

9.Lombok

使用步骤:

1.在IDEA中安装Lombok插件!

2.在项目中导入Lombok的jar包

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
    <scope>provided</scope>
</dependency>

常用注解:

@Setter :注解在类或字段,注解在类时为所有字段生成setter方法,注解在字段上时只为该字段生成setter方法。

@Getter :使用方法同上,区别在于生成的是getter方法。

@ToString :注解在类,添加toString方法。

@EqualsAndHashCode: 注解在类,生成hashCode和equals方法。

@NoArgsConstructor: 注解在类,生成无参的构造方法。

@RequiredArgsConstructor: 注解在类,为类中需要特殊处理的字段生成构造方法,比如final和被@NonNull注解的字段。

@AllArgsConstructor: 注解在类,生成包含类中所有字段的构造方法。

@Data: 注解在类,生成setter/getter、equals、canEqual、hashCode、toString方法,如为final属性,则不会为该属性生成setter方法。

@Slf4j: 注解在类,生成log变量,严格意义来说是常量。

10.多对一处理

image-20200730170125265

  • 多个学生,对应一个老师

  • 对于学生这边而言,关联...多个学生,关联一个老师【多对一】

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

测试环境搭建

1.导入lombok

2.新建实体类 Teacher,Student

3.建立Mapper接口

4.建立Mapper.xml文件

5.在核心配置文件中绑定注册我们的Mapper接口或者文件!

6.测试查询是否能够成功!

 

按照查询嵌套处理

<mapper namespace="com.dong.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 property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id=#{id}
    </select>

按照结果嵌套处理

<!--    按照结果查询-->
    <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.一对多处理

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

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

1.环境搭建

实体类

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

按照结果嵌套处理

<select id="getTeacher" resultMap="teacherStudent">
    select s.id sid,s.name sname,t.id tid,t.name tname
    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"/>
    <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 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 1000s

面试高频

  • Mysql引擎

  • InnoDB底层原理

  • 索引

  • 索引优化!

12、动态SQL

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

搭建环境

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. 编写实体类

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

IF

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

choose(when,otherwise)

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

<select id="queryBlogIf" parameterType="map" resultType="blog">
    select * from blog 
    <where>
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
</select>
<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>

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

if

where , set , choose ,when

 

SQL片段

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

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

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

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

<update id="updateBlog" parameterType="map">
    update  blog
    <set>
       <include refid="if-title-author"></include>
    </set>
    where id = #{id}
</update>

注意事项:

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

  • 不要存在where标签

Foreach

<select id="queryBlogForeach" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <foreach collection="ids" item="id" open="(" close=")" separator="or">
            id = #{id}
        </foreach>
    </where>
</select>
@Test
public void queryBlogForeach(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    ArrayList<Integer> ids = new ArrayList<Integer>();
    ids.add(1);
    ids.add(2);
    ids.add(3);
    map.put("ids",ids);
    List<Blog> blogs = mapper.queryBlogIf(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}

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

建议:

  • 先在Mysql中写出完整的SQL,再对应的去修改成为我们的动态SQL

13.缓冲

13.1简介

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

1.什么是缓存【Cache】?

  • 存在内存中的临时数据。

  • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓冲中查询,从而提高查询效率,解决了高并发系统的性能问题。

2.为什么使用缓存?

  • 减少和数据库的交互次数,减少系统开销,提高系统效率。

3.什么样的数据能使用缓存?

  • 经常查询并且不经常改变的数据。

13.2Mybatis缓存

  • MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。

  • MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存

    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)

    • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。

    • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以同过实现Cache接口来自定义二级缓存

13.3、一级缓存

  • 一级缓存也叫本地缓存:SqlSession

    • 与数据库同一次会话期间查询到的数据会放在本地缓冲中。

    • 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库;

缓存失效的情况:

1.查询不同的东西

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

3.查询不同的Mapper

4.手动清除缓存!SqlSession.clearCache

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

13.4二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存

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

  • 工作机制

    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;

    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;

    • 新的会话查询信息,就可以从二级缓存中获取内容;

    • 不同的mapper查出的数据会放在自己对应的缓存(map)中

步骤:

1.开启全局缓存

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

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

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

也可以自定义参数

<!--在当前Mapper.xml中使用二级缓存-->
<cache eviction="FiFO" 输入输出策略
       flushInterval="60000"
       size="512"  缓存数量
       readOnly="true"  是否只读

image-20200801132358657

小结:

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

  • 所有的数据都会先放在一级缓存中;

  • 只有当会话提交,或者关闭的时候,才会提交道二级缓存中!

 

1.35缓存原理

image-20200801133527838

13.6自定义缓存- ehcache

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

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

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

 

14.自我总结

mybatis创建步骤:

1.创建maven项目

在pom.xml文件中导入需要的jar包

<!--导入依赖-->
<dependencies>

    <!--mysql驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>

    <!--mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.4</version>
    </dependency>

    <!--junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
    </dependency>

    <!--日志log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

    <!--lombok包-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

2.删除src文件

重新创建一个Module文件,(这样操作,创建的文新项目为子工程,jar包自动导入到子工程中);在resources中创建Mybatis-config.xml配置文件,并且导入外部数据库配置文件db.properties,log4j.properties文件为日志文件,可在配置文件中用标准日志

Mybatis-config.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>

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

    <settings>
        <!--设置日志-->
        <!--  标准日志工厂实现      -->
        <!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
        <setting name="logImpl" value="LOG4J"/>
        <!--设置开启数据库字段下划线和java属性驼峰命名规则映射-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!--别名-->
    <typeAliases>
        <package name="com.dong.pojo"/>
    </typeAliases>
    <!--环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--映射路径/类-->
    <mappers>
        <mapper class="com.dong.dao.UserMapper"/>
    </mappers>
</configuration>

db.properties

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

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/dong.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.编写实体类User,对应的接口UserMapper以及接口配置文件UserMapper.xml

User

//导入Lombokjar包后利用注解完成getset tostring等方法
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}

UserMapper

public interface UserMapper {
    List<User> getUserList();
}

UserMapper.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">

<mapper namespace="com.dong.dao.UserMapper">
    <select id="getUserList" resultType="user">
        select * from user
    </select>
</mapper>

4.编写工具类utils

封装工具类MybatisUtils,用SqlSession来操作数据库

public class MybatisUtils {
    //获取SqlSessionFactory
    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 getSqlSession(){
        return sqlSessionFactory.openSession();
    }

    }

 

5.测试

public class MyTest {
    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        //sqlSession.clearCache();//手动清除缓存
        sqlSession.close();
    }
}

 

posted @ 2020-08-01 15:21  小小细胞  阅读(442)  评论(0编辑  收藏  举报