【2020-05-12】Mybatis学习笔记Part-2

Jammm
2020-05-12 / 0 评论 / 489 阅读 / 正在检测是否收录...

Powered By JamPang

QQ:847885907

https://jampang.cn/


其他部分

第一部分链接:点击访问
第三部分链接:点击访问


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

项目名:mybatis-03

5.1、问题

数据库中的字段:id,name,pwd

新建一个项目,拷贝之前的,测试实体类字段不一致的情况:id,name,password

public class User {
    private int id;
    private String name;
    private String password;
}

测试出现问题

User{id=1, name='jam', pwd='null'}
// select * from mybatis.user where id = ##{id}
//类型处理器
// select id,name,pwd from mybatis.user where id = ##{id}

解决问题:

  • 起别名

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

5.2、resultMap

结果集映射

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

<!-- id查询 -->
<select id="getUserById" parameterType="int" resultMap="UserMap">
    select * from mybatis.user where id = ##{id}
</select>
  • resultMap 元素是 MyBatis 中最重要最强大的元素
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
  • ResultMap 的优秀之处——你完全可以不用显式地配置它们。【也就是字段不一样的地方需要申明】

    <!--结果集映射-->
    <resultMap id="UserMap" type="User">
        <!--column数据库中的字段,property实例类中的属性-->
        <result column="pwd" property="password"/>
    </resultMap>
  • 如果这个世界总是这么简单就好了。**

6、日志

项目:mybatis-04

6.1、日志工厂

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

曾经:sout、debug

现在日志工厂。

设置名描述有效值
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J、LOG4J、LOG4J2、JDK_LOGGING、COMMONS_LOGGING、STDOUT_LOGGING、NO_LOGGING

需要掌握:LOG4J、STDOUT_LOGGING

在Mybatis中具体使用哪个日志,需要在设置中设定。

STDOUT_LOGGING标准日志输出

在mybatis核心配置文件中,配置我们的日志。[mybatis-config.xml]

配置代码:

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

输出结果:

Created connection 1859039536.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@6eceb130]
==>  Preparing: select * from mybatis.user where id = ? 
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, jam, 123
<==      Total: 1
User{id=1, name='jam', pwd='123'}
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@6eceb130]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@6eceb130]
Returned connection 1859039536 to pool.

6.2、Log4j

什么是Log4j?

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台文件GUI组件
  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
  • 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
  1. 先导入loh4j的包【可在当前Maven模块的pom.xml中加】

    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
  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/jamlog.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为日志的实现 [mybatis-config.xml]

    <!-- settings -->
        <settings>
            <setting name="logImpl" value="LOG4J"/>
        </settings>
  4. Log4j的使用:直接测试运行

    [org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    [org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    [org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
    [org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
    [org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
    [org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
    [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Opening JDBC Connection
    Sat Apr 25 01:07:49 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    [org.apache.ibatis.datasource.pooled.PooledDataSource]-Created connection 2007331442.
    [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@77a57272]
    [com.jam.dao.UserMapper.getUserById]-==>  Preparing: select * from mybatis.user where id = ? 
    [com.jam.dao.UserMapper.getUserById]-==> Parameters: 1(Integer)
    [com.jam.dao.UserMapper.getUserById]-<==      Total: 1
    User{id=1, name='jam', pwd='123'}
    [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@77a57272]
    [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@77a57272]
    [org.apache.ibatis.datasource.pooled.PooledDataSource]-Returned connection 2007331442 to pool.

简单使用

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

    public class UserDaoTest {
    
        static Logger logger = Logger.getLogger(UserDaoTest.class);
    
        @Test
        public void testLoh4j(){
            logger.info("info:进入了testLog4j");
            logger.debug("debug:进入了testLog4j");
            logger.error("error:进入了testLog4j");
        }
    
    }
  3. 日志级别

    logger.info("info:进入了testLog4j");
    logger.debug("debug:进入了testLog4j");
    logger.error("error:进入了testLog4j");

7、分页

项目:mybaits-04

思考:为什么要分页?

  • 减少数据的处理量。

7.1、使用Limit分页

select * from user limit startIndex,pageSize;

使用Mybatis实现分页,核心SQL

  1. 接口

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

    <!--分页-->
    <select id="getUserByLimit" parameterType="map" resultMap="UserMap">
        select * from mybatis.user limit ##{startIndex},##{pageSize}
    </select>
  1. 测试

     @Test
    public void getUserByLimit(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("startIndex",1);
        map.put("pageSize",2);
    
        List<User> userList = mapper.getUserByLimit(map);
        for (User user : userList) {
            System.out.println(user);
        }
    
        sqlSession.close();
    }
    

7.2、RowBounds

不再使用SQL实现分页

  1. 接口

    //分页2
    List<User> getUserByRowBounds();
  2. Mapper.xml

    <!--分页2-->
    <select id="getUserByRowBounds" resultMap="UserMap">
        select * from mybatis.user
    </select>
  3. 测试

    @Test
    public void getUserByRowBounds(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
    
        //RowBounds实现
        RowBounds rowBounds = new RowBounds(1, 2);
    
        //通过Java代码层面实现分页
        List<User> userList = sqlSession.selectList("com.jam.dao.UserMapper.getUserByRowBounds",null,rowBounds);
    
        for (User user : userList) {
            System.out.println(user);
        }
    
        sqlSession.close();
    }

7.3、分页插件

官方文档:https://pagehelper.github.io/

8、使用注解开发

8.1、面向接口编程

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

关于接口的理解

  • 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
  • 接口的本身反映了系统设计人员对系统的抽象理解。
  • 接口应有两类:

    • 第一类是对一个个体的抽象,它可对应为-一个抽象体(abstract class);
    • 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface) ;
  • 一个个体有可能有多个抽象面。抽象体与抽象面是有区别的。

三个面向区别

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

8.2、使用注解开发

项目:mybatis-05

  1. 注解在接口上实现 UserMapper.java

    //获取用户
    @Select("select * from user")
    List<User> getUsers();
  2. 需要在核心配置文件中绑定接口

    <!--绑定接口-->
    <mappers>
        <mapper class="com.jam.dao.UserMapper"/>
    </mappers>
  3. 测试

    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
    
        //底层主要应用反射
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUsers();
    
        for (User user : userList) {
            System.out.println(user);
        }
    
        sqlSession.close();
    
    }

本质:反射机制实现

底层:动态代理

image-20200426174102331

Mybatis详细的执行流程!

mmexport1588156809470

8.3、CURD

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

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

编写接口和注解

//获取用户
@Select("select * from user")
List<User> getUsers();

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

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

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

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

测试

注意:必须将接口注册绑定到核心配置文件中

8.4、关于@Param注解

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

##{},${}的区别

  • {}能够防止sql注入

  • ${}方式无法防止sql注入
  • $一般用来传入数据库对象,比如数据表名
  • 能用##{}时尽量用##{}

9、Lombok

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.
  • java library
  • plugs
  • build tools
  • with one annotation your class

使用步骤:

  1. 在IDEA中安装Lombok插件
  2. 在项目中导入Lombok的jar包

    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.10</version>
    </dependency>
  3. 注解

    @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
    @val
    @var
    experimental @var
    @UtilityClass

说明:

@Data:无参构造、get、set、toString、hashcode、equals
@AllArgsConstructor 有参构造
@NoArgsConstructor  无参构造
@EqualsAndHashCode
@ToString
@Getter

10、多对一处理

项目:mybatis-06

多对一:

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

数据库

CREATE TABLE `teacher` (
    `id` INT(10) NOT NULL,
    `name` VARCHAR(30) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO teacher(`id`, `name`) VALUES (1, '庞老师');

CREATE TABLE `student` (
    `id` INT(10) NOT NULL,
    `name` VARCHAR(30) DEFAULT NULL,
    `tid` INT(10) DEFAULT NULL,
    PRIMARY KEY (`id`),
    KEY `fktid` (`tid`),
    CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;


INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');

Student类 (省略了构造函数、Setter/Getter)

public class Student {
    private int id;
    private String name;

    //学生需要关联一个老师
    private Teacher teacher;

}

Teacher类(省略了构造函数、Setter/Getter)

public class Teacher {
    private int id;
    private String name;
}

10.1、测试环境搭建

  1. 导入Lombok
  2. 新建实体类Teacher,Student
  3. 建立Mapper接口
  4. 建立Mapper.xml文件【在Resources目录下需要一级一级建立文件夹】
  5. 在核心配置中绑定注册我们的Mapper接口或者文件
  6. 测试查询是否能成功

10.2、按照查询嵌套处理

<!--
   思路:
        1. 查询所有的学生信息
        2. 根据查询出来的学生的tid,寻找对应的老师  子查询
-->

<select id="getStudent" resultMap="StudentTeacher">
    select * from student
</select>

<resultMap id="StudentTeacher" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--复杂的属性
        对象:association
        集合:collection
    -->
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>

<select id="getTeacher" resultType="Teacher">
    select * from teacher where id = ##{id}
</select>

10.3、按照结果嵌套处理

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

项目:mybatis-07

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

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

11.1、搭建环境

实体类

//Teacher类
public class Teacher {
    private int id;
    private String name;

    //一个老师拥有多个学生
    private List<Student> students;
    
}

//Student类
public class Student {
    private int id;
    private String name;
    private int tid;

}

11.2、按照查询嵌套处理

<select id="getTeacher2" resultMap="TeacherStudent2">
    select * from mybatis.teacher where id = ##{tid}
</select>

<resultMap id="TeacherStudent2" type="Teacher">
    <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>

<select id="getStudentByTeacherId" resultType="Student">
    select * from mybatis.student where tid = ##{tid}
</select>

11.3、按照结果嵌套处理

<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
    select s.id sid,s.name sname,t.name tname,t.id tid
    from student s,teacher t
    where s.tid = t.id and t.id = ##{tid}
</select>

<resultMap id="TeacherStudent" type="Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--复杂的属性
    对象:association
    集合:collection
    集合中的泛型信息,使用ofType获取
    -->
    <collection property="students" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>

11.4、小结

  1. 关联 - association 【多对一】
  2. 集合 - collection 【一对多】
  3. javaType & ofType

    1. JavaType:用来指定实体类中属性的类型
    2. ofType:用来指定映射到List或者集合中的pojo类型,泛型中的约束类型

注意点:

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

11.5、面试高频

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

第二部分结束,第三部分:点击访问

本文共 1942 个字数,平均阅读时长 ≈ 5分钟
0

打赏

海报

正在生成.....

评论 (0)

取消