文章目录

  • Mybatis入门
    • 1.为什么要使用mybatis?
    • 2.ORM
    • 3.mybatis简介
    • 4.mybatis框架
    • 5.mybatis入门程序
      • 5.1搭建环境
      • 5.2 配置log4j
      • 5.3 配置SqlMapConfig.xml
      • 5.4 创建bean对象
      • 5.5 配置映射文件
      • 5.6 加载映射文件
      • 5.7 编写代码
    • 6.完成CRUD操作
      • 6.1 映射文件
      • 6.2 编码
    • 7.总结原生Dao的开发的缺陷
    • 8.Mapper代理方法
      • 8.1 mapper代理开发规范
      • 8.2mapper代理开发入门
        • 8.2.1 映射文件
        • 8.2.2 mapper接口
        • 8.2.3 测试类
    • 9.SqlMapConfig.xml详解
      • 9.1 properties
      • 9.2 settings全局参数配置
      • 9.3 typeAliases(别名)(重点)
        • 9.3.1 默认别名
        • 9.3.2 自定义别名
      • 9.4 typeHandlers(类型处理器)
      • 9.5 mappers(映射器)
        • 9.5.1 resource加载映射
        • 9.5.2 mapper接口加载
        • 9.5.3 批量加载mapper
    • 10.动态sql
      • 10.1 where if
      • 10.2 sql片段
      • 10.3 foreach

Mybatis入门

1.为什么要使用mybatis?

总结JDBC存在的问题:

1.数据库连接的时候,使用的时候就创建,不适用立刻释放,对数据库进行了频繁的链接开启和关闭。造成了数据库资源的浪费。

解决方案:使用数据库连接池

2.将sql语句硬编码(写在)到java代码中,如果sql语句发生了改变。需要重新编译java代码。不利于系统的维护。

解决方案:将sql放入在xml文件中,那么即使sql发生了改变也不需要对java代码重新编译

3.jdbc中sql传入参数和取出ResultSet中的值都存在硬编码问题。

解决方案:sql参数的问题可以配置到xml中。至于ResultSet中查询到的数据集自动映射成java对象。

2.ORM

3.mybatis简介

mybatis是一个持久化层的框架。是Apache下的顶级项目。mybatis主要实现让程序员把精力放到sql上,通过mybatis提供的映射方式,自动灵活的生成对应的sql以及自动把数据集映射到java对象上。

4.mybatis框架

5.mybatis入门程序

5.1搭建环境

创建Java项目并且导入相关依赖和相应的包目录。

5.2 配置log4j

创建log4j的配置文件并且完成配置(可以复制)

# Global logging configuration
# ERROR WARN INFO DEBUG
log4j.rootLogger=DEBUG, a
# Console output...
log4j.appender.a=org.apache.log4j.ConsoleAppender
log4j.appender.a.layout=org.apache.log4j.PatternLayout
log4j.appender.a.layout.ConversionPattern=%5p [%t] - %m%n

5.3 配置SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><properties resource="jdbc.properties"></properties><!-- mbatis的运行环境,后期此配置会被遗弃 --><environments default="development"><environment id="development"><!-- 配置事务 --><transactionManager type="JDBC"></transactionManager><!-- 配置数据源 --><!-- type:使用的数据库连接池 --><dataSource type="POOLED"><property name="driver" value="${driverClassName}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment></environments>
</configuration>

5.4 创建bean对象

public class Emp {private int eid;private String ename;private String sex;private int age;
}
//省略get set方法

5.5 配置映射文件

<?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:命名空间。作用是对sql进行分类化管理。注意:在mapper代理开发中 namespace有特别的作用 -->
<mapper namespace="emptest"><!-- id:唯一标识resultType:指定sql输出的结果集映射的Java对象类型parameterType:指定输入参数的数据类型--><select id="findAllEmp" resultType="com.lxk.bean.Emp">select * from emp</select>
</mapper>

5.6 加载映射文件

<!-- 加载映射文件 -->
<mappers>
<mapper resource="emp.xml"/>
</mappers>

5.7 编写代码

public void findAll() throws IOException {//获取配置文件流(加载配置文件)InputStream inputStream = Resources.getResourceAsStream("MyBatisConfig.xml");//获取会话工厂SqlSessionFactory  sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);//获取会话SqlSession session = sqlSessionFactory.openSession();//通过sqlsession来操作数据库List<Emp> list = session.selectList("emptest.findAllEmp");//关闭sessionsession.close();for (Emp emp : list) {System.out.println(emp);}}

6.完成CRUD操作

6.1 映射文件

<?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:命名空间。作用是对sql进行分类化管理(sql隔离)。注意:在mapper代理开发中 namespace有特别的作用 -->
<mapper namespace="emptest"><!-- id:唯一标识resultType:指定sql输出的结果集映射的Java对象类型parameterType:指定输入参数的数据类型--><select id="findAllEmp" resultType="com.lxk.bean.Emp">select * from emp</select><!-- #{}:代表一个占位符。如果传入的参数是基本数据类型和String,那么#{}里面随便写如果传入的参数是对象类型,那么#{}里面需要写成对象的属性名${}:代表原样拼接。如果传入的参数是基本数据类型和String,那么${}里面必须写成value如果传入的参数是对象类型,那么#{}里面需要写成对象的属性名一般不推荐使用这种方式。因为此方式可能会造成sql注入--><select id="findEmpById" parameterType="java.lang.Integer" resultType="com.lxk.bean.Emp">select * from emp where eid = #{eid}</select><select id="login" parameterType="java.lang.String" resultType="com.lxk.bean.Emp">select * from emp where ename="马二" and sex='${value}'</select><select id="findlikename" parameterType="java.lang.String" resultType="com.lxk.bean.Emp">select * from emp where ename like '%${value}%'<!-- select * from emp where ename like #{ename} --></select><insert id="addEmp" parameterType="com.lxk.bean.Emp">insert into emp (ename,sex,age) value(#{ename},#{sex},#{age})</insert><update id="updateById" parameterType="com.lxk.bean.Emp">update emp set ename=#{ename},sex=#{sex},age=#{age} where eid=#{eid}</update><delete id="deleteById" parameterType="java.lang.Integer">delete from emp where eid=#{eid}</delete>
</mapper>

6.2 编码

package com.lxk.dao;import java.io.IOException;
import java.io.InputStream;
import java.util.List;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;import com.lxk.bean.Emp;public class EmpDao {SqlSession session;@Beforepublic void getsession() throws IOException {//获取配置文件流(加载配置文件)InputStream inputStream = Resources.getResourceAsStream("MyBatisConfig.xml");//获取会话工厂SqlSessionFactory  sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);//获取会话session = sqlSessionFactory.openSession();}//查询所有@Testpublic void findAll() {//通过sqlsession来操作数据库List<Emp> list = session.selectList("emptest.findAllEmp");//关闭sessionsession.close();for (Emp emp : list) {System.out.println(emp);}}//根据ID进行查询@Testpublic void findEmpById() {Emp emp = session.selectOne("emptest.findEmpById", 8);System.out.println(emp);}//sql注入@Testpublic void login() {Emp emp = session.selectOne("emptest.login", "男' or '1=1");System.out.println(emp);}//模糊查询@Testpublic void findEmpLikeName() {List<Emp> list = session.selectList("emptest.findlikename", "二");//使用#{}的方式来实现模糊查询/*List<Emp> list = session.selectList("emptest.findlikename", "%二%");*/for (Emp emp : list) {System.out.println(emp);}}//添加一个新员工@Testpublic void addEmp() {Emp emp = new Emp();emp.setEname("xxx");emp.setSex("女");emp.setAge(5);session.insert("emptest.addEmp",emp);//提交事务session.commit();}//根据ID修改员工信息@Testpublic void updateByID() {Emp emp = new Emp();emp.setEid(9);emp.setEname("xx");emp.setSex("女");emp.setAge(65);session.update("emptest.updateById", emp);session.commit();}//根据ID删除指定员工@Testpublic void deleteById() {session.delete("emptest.deleteById", 9);session.commit();}
}

7.总结原生Dao的开发的缺陷

1.sqlsession调用statement的id的时候还是存在硬编码问题

2.sqlsession调用方法的时候传入变量,由于方法使用Object类型来进行接收,所以即使变量类型不匹配,那么编译阶段也不会出现错误。

8.Mapper代理方法

8.1 mapper代理开发规范

程序员需要编写的有mapper.xml映射文件,还有一个mapper接口。程序员在编写mapper接口的时候只需要遵循mapper代理开发的规范,那么mybatis会自动生成mapper接口的实现类的代理对象。

1.mapper.xml(映射文件)中的namespace等于mapper接口的地址

2.mapper接口中的方法名和mapper.xml中的statement的ID保持一致

3.mapper接口中的输入参数类型和mapper.xml中的statement的parameterType的指定类型保持一致

4.mapper接口中的返回值类型和mapper.xml中的Statement的resultType的指定类型保持一致

5.保证mapper.xml和mapper接口在同一目录下并且名字相同

8.2mapper代理开发入门

8.2.1 映射文件
<?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.lxk.mapper.EmpMapper"><select id="findAllEmp" resultType="com.lxk.bean.Emp">select * from emp</select>
</mapper>
8.2.2 mapper接口
public interface EmpMapper {public List<Emp> findAllEmp();
}
8.2.3 测试类
public static void main(String[] args) throws IOException {//以后service层来调用mapperInputStream inputStream = Resources.getResourceAsStream("MyBatisConfig.xml");SqlSessionFactory  sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);SqlSession session = sqlSessionFactory.openSession();//获取mapper实现类的代理对象EmpMapper mapper = session.getMapper(EmpMapper.class);//以后service层只需要编写下面这一句话。  上面获取的过程全部交给spring处理List<Emp> list = mapper.findAllEmp();for (Emp emp : list) {System.out.println(emp);}}

9.SqlMapConfig.xml详解

mybatis的全局配置文件SqlMapConfig.xml。里面可以配置一下内容:

properties(加载资源文件)

settings(全局配置参数)

typeAliases(类型别名)

typeHandlers(类型处理器)

objectFactory(对象工厂)

plugins(插件)

environments(环境集合属性对象)

​ transactionManager(事务管理)

​ dataSource(数据源)

mappers(映射器)

注意:在此配置文件中配置有先后顺序的规定

9.1 properties

一般用于加载数据库的资源文件。这样就避免了配置文件中对数据库连接使用硬编码。使用此配置可以灵活的概念数据库的链接参数

资源文件:

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/jsdb?characterEncoding=utf8&serverTimezone=Asia/Shanghai
username=root
password=1234

配置使用:

<!--加载资源文件-->
<properties resource="jdbc.properties"></properties>
<!--使用资源文件-->
<property name="driver" value="${driverClassName}"/>

properties特性:

<properties resource="jdbc.properties"><property name="driverClassName" value="com.mysql.jdbc.Driver"/>
</properties>
<!--mybatis中对properties是有加载顺序的。首先加载properties元素体内定义的属性,然后再去读取properties元素中resource或url属性指向的文件。它会覆盖已经读取的同名属性。
使用建议:不要在元素体内添加任何属性和属性值,把属性定义properties文件中。
-->

9.2 settings全局参数配置

mybatis框架在运行的时候可以调整一些运行参数。比如开启二级缓存,开启延迟加载(lazy)。配置全局参数会影响mybatis的运行行为。

<!--了解-->
<settings><!--关闭缓存--><setting name="cacheEnabled" value="false"/><!--关闭延迟加载--><setting name="lazyLoadingEnabled" value="false"/>
</settings>

9.3 typeAliases(别名)(重点)

应用场景:

在mapper.xml中,程序员定义很多statement,statement配置resultType和parameterType指定输入和输出的参数类型。如果不是使用别名需要编写输入输出类型的全路径。为了解决这个全路径问题mybatis可以配置别名,方便开发。

mybatis中别名分为两种:

9.3.1 默认别名
映射的类型     别名
Date        date
Boolean     boolean
Float       float
Double      double
Integer     integer/int
Short       short
Long        long
Byte        byte
String      string
----------------------
int         _int/_integer
byte        下面都同理
long
short
double
float
boolean
9.3.2 自定义别名

9.3.2.1 单个别名定义

<typeAliases><!-- type:类型的全路径alias:别名--><typeAlias type="com.lxk.bean.Emp" alias="emp"/>
</typeAliases>
<!--企业中bean太多,使用此配置不合适-->

9.3.2.2 批量别名定义

<typeAliases><!--批量定义别名mybatis自动扫描指定的包。别名就是类名(首字母大小写都可以)--><package name="com.lxk.bean"/>
</typeAliases>

9.4 typeHandlers(类型处理器)

mybatis中使用typeHandlers完成jdbc类型和java类型的转换。

通常不需要手动配置。因为mybatis提供的类型处理器已经可以满足开发使用。

9.5 mappers(映射器)

9.5.1 resource加载映射
<mappers><!--加载单个映射文件--><mapper resource="com/lxk/mapper/EmpMapper.xml"/>
</mappers>
9.5.2 mapper接口加载
<mappers><!--通过mapper接口加载映射文件(前提:使用mapper代理开发)遵守一些规则:mapper接口的名字和mapper。xml映射的名字一致并且在同一目录下--><mapper class="com.lxk.mapper.EmpMapper"/>
</mappers>
9.5.3 批量加载mapper
<mappers><!--通过mapper接口加载映射文件(前提:使用mapper代理开发)遵守一些规则:mapper接口的名字和mapper。xml映射的名字一致并且在同一目录下--><package name="com.lxk.mapper"/>
</mappers>

10.动态sql

mybaits对sql可以进行灵活的操作。通过表达式进行判断对sql进行灵活的拼接,组装。

10.1 where if
<select id="findEmpBySexAndAge" resultType="emp" parameterType="emp">select * from emp <!-- 后面所有的if都不成立 where不会出现去自动去掉条件后的第一个and--><where><if test="sex!=null">and sex=#{sex}</if><if test="age!=null and age!=0">and age=#{age}</if></where>
</select>
10.2 sql片段

将sql中的一部分抽离出来组成一个sql片段。其他statement可以引用这个sql片段,便于开发。

<!-- 创建sql片段 -->
<sql id="findall">select * from emp
</sql>
<!-- 创建sql片段2 -->
<sql id="findsexandage_where"><where><if test="sex!=null">and sex=#{sex}</if><if test="age!=null and age!=0">and age=#{age}</if></where>
</sql>
<select id="findEmpBySexAndAge" resultType="emp" parameterType="emp"><!-- 引入sql片段 --><include refid="findall"/><!-- 引入sql片段2 --><include refid="findsexandage_where"/>
</select>
10.3 foreach

使用动态sql实现:select * from emp where eid=1 or eid=3 or eid=8

<select id="findEmpByIds" resultType="emp" parameterType="empids"><!-- select * from emp where eid=1 or eid=3 or eid=8 --><include refid="findall"/><where><if test="ids!=null"><!-- collection:指定需要被遍历的属性 item:每次遍历生成的对象open:开始遍历的时候需要拼接的串close:结束遍历的时候需要拼接的串separator:遍历每两个对象之间需要拼接的串--><foreach collection="ids" item="id" separator="or">eid=#{id}</foreach></if></where>
</select>

使用动态sql实现:select * from emp where eid in (1,3,8)

<select id="findEmpByIds" resultType="emp" parameterType="empids"><!-- select * from emp where eid in (1,3,8)--><include refid="findall"/><where><if test="ids!=null">eid in<foreach collection="ids" item="id" open="(" close=")" separator=",">#{id}</foreach></if></where>
</select>

Mybatis学习笔记——Mybatis入门相关推荐

  1. mybatis学习笔记(3)-入门程序一

    2019独角兽企业重金招聘Python工程师标准>>> mybatis学习笔记(3)-入门程序一 标签: mybatis [TOC] 工程结构 在IDEA中新建了一个普通的java项 ...

  2. MyBatis多参数传递之Map方式示例——MyBatis学习笔记之十三

    前面的文章介绍了MyBatis多参数传递的注解.参数默认命名等方式,今天介绍Map的方式.仍然以前面的分页查询教师信息的方法findTeacherByPage为例(示例源代码下载地址:http://d ...

  3. Mybatis学习笔记(二) 之实现数据库的增删改查

    开发环境搭建 mybatis 的开发环境搭建,选择: eclipse j2ee 版本,mysql 5.1 ,jdk 1.7,mybatis3.2.0.jar包.这些软件工具均可以到各自的官方网站上下载 ...

  4. MyBatis多参数传递之混合方式——MyBatis学习笔记之十五

    在本系列文章的<MyBatis多参数传递之Map方式示例>一文中,网友mashiguang提问如下的方法如何传递参数:public List findStudents(Map condit ...

  5. mybatis学习笔记(13)-延迟加载

    2019独角兽企业重金招聘Python工程师标准>>> mybatis学习笔记(13)-延迟加载 标签: mybatis [TOC] resultMap可以实现高级映射(使用asso ...

  6. mybatis学习笔记(7)-输出映射

    2019独角兽企业重金招聘Python工程师标准>>> mybatis学习笔记(7)-输出映射 标签: mybatis [TOC] 本文主要讲解mybatis的输出映射. 输出映射有 ...

  7. ant的下载与安装——mybatis学习笔记之预备篇(一)

    看到这个标题是不是觉得有点奇怪呢--不是说mybatis学习笔记吗,怎么扯到ant了?先别急,请容我慢慢道来. mybatis是另外一个优秀的ORM框架.考虑到以后可能会用到它,遂决定提前学习,以备不 ...

  8. mybatis学习笔记--常见的错误

    原文来自:<mybatis学习笔记--常见的错误> 昨天刚学了下mybatis,用的是3.2.2的版本,在使用过程中遇到了些小问题,现总结如下,会不断更新. 1.没有在configurat ...

  9. mybatis学习笔记(1)-对原生jdbc程序中的问题总结

    2019独角兽企业重金招聘Python工程师标准>>> mybatis学习笔记(1)-对原生jdbc程序中的问题总结 标签:mybatis [TOC] 本文总结jdbc编程的一般步骤 ...

最新文章

  1. 十大成长型机器人技术大盘点
  2. 程序员常用的六大技术博客类
  3. 触发Full GC执行的情况 以及其它补充信息
  4. vivox21升级鸿蒙,vivo X21i相机规格再升级,加持AI成又一拍照神器
  5. Python正则表达式,简单20个用例学习
  6. 谷歌的网页排序算法(PageRank Algorithm)
  7. 按关键字截取linux日志,linux awk截取数据,如何根据第二部分数据的关键字‘aaaaa’获取整串数据...
  8. chrome gwt1.7_快速提示:使用Chrome开发工具调试GWT应用程序
  9. DNS IP DOMAIN 详解
  10. 注解形式控制器(4) 数据绑定
  11. 智能计算机的功能是什么问题,人工智能在电脑系统的作用
  12. java中enum类型的使用
  13. 第三节:SpringBoot中web项目推荐目录结构
  14. 深入理解计算机系统(1.3)------操作系统的抽象概念
  15. 【干货】--基于Python的文本情感分类
  16. word模板文档替换,解决并发导致替换失败
  17. 我们为什么不画高保真原型图
  18. html5如何快速根据psd,微页h5制作工具怎么快速导入PSD源文件?
  19. Vue实现省、市、县三级联动
  20. 关于跳跃连接 卷积网络

热门文章

  1. C语言 不使用strcpy 函数实现字符串复制功能
  2. python为什么是蛇的天敌_蛇遇猪就得哭什么意思 猪为什么是蛇的天敌
  3. Windows xp Home(家庭版)/Professional(专业版)微软原版镜像(附校验值)
  4. 蓝牙定位方案之Ibeacon定位技术解决方案-新导智能
  5. 【转】一个网站都需要哪些备案
  6. 华为无线设备配置用户CAC
  7. 基于RabbitMQ 的 Web MQTT插件进行前端消息实时推送
  8. JForum论坛源码部署
  9. ASP中LIKE模糊查
  10. 探索 Word 2007 开发 II(二):引用 Amazon 图书信息