Mybatis

Mybatis

持久层框架

为什么需要Mybatis

1、方便
2、传统的JDBC代码太复杂,简化,框架,自动化
3、帮助程序员将数据存入到数据库中
4、不用Mybatis也可以,更容易上手
5、优点
1.简单易学
2.灵活
3.sql和代码的分离,提高了可维护性
4.提供映射标签,支持对象与数据库的orm字段关系映射
5.提供对象关系映射标签,支持对象关系组建维护
6.提供xml标签,支持编写动态sql

第个Mybatis程序

思路:搭建环境–>导入Mybatis–>编写代码–>测试

搭建环境

1、新建一个普通的maven项目
2、删除src目录
3、导入maven依赖
导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.kuang</groupId>
    <artifactId>Mybatis_Study1</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>mybatis_01</module>
    </modules>
    <!--导入依赖-->
    <!--mysql驱动-->
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/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>
        </dependency>
    </dependencies>

</project>

创建模块

编写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;useUnicode=true&amp;characterEncoding=UTF-8/test?useUnicode=true&amp;characterEncoding=UTF-8&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
 <!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册-->
    <mappers>
        <mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>
</configuration>

编写mybatis工具类

//SqlSessionFactory --> sqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            //使用Mybatis获取sqlSession对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //既然有了SqlSessionFactory,顾名思义,我们就可以获得SqlSession的实例了。
    //SqlSession完全包含了面向数据库执行SQL命令所需的所有方法。
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

编写代码

实体类

//实体类
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接口


import com.kuang.pojo.User;

import java.util.List;

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.kuang.dao.UserDao">
    <!--select查询语句-->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user
    </select>
</mapper>

测试

配置文件导出失败问题

在build中配置resources,来防止我们资源导出失败的问题
在pom.xml中添加

<!--防止乱码-->
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>


public class UserDaoTest {
    @Test
    public void test(){
        //获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //执行SQL
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();

    }
}

MapperRegistry是什么?
核心配置文件中注册mappers

CRUD

namespace

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

select

选择,查询语句
id:就是对应的namespace中的方法名;
resultType:Sql语句执行的返回值;
parameterType:参数类型

1、编写接口

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

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

<select id="getUserById" parameterType="int" resultType="com.kuang.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 user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }
Insert
update
Delete

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

分析错误

标签不要匹配错误
resource 绑定mapper,需要路径
程序配置文件必须符合规范

万能的Map

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

int addUser2(Map<String,Object> map);
    <insert id="addUser2" parameterType="map">
        insert into mybatis.user(id, name, pwd) values (#{userid},#{userName},#{password});
    </insert>
  @Test
    public void addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userid",5);
        map.put("userName","Hello");
        map.put("password","2234524");
        mapper.addUser2(map);
        sqlSession.commit();
        sqlSession.close();
    }

Map传递参数,直接在sql中取出key即可
对象传递参数,直接在sql中取对象的属性即可
只有一个基本类型情况下,可以直接不写
多个参数用Map,或者注解

模糊查询怎么写?
1、Java代码执行的时候,传递通配符%%

List<User> userList = mapper.getUserLike("%李%");

2、在Sql拼接中使用通配符

 select * from mybatis.user where id = #{helloId} and name="%"#{name}"%";

配置解析

1、核心配置文件

mybatis-config.xml
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。

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

MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
学会使用配置多套运行环境
Mybatis默认的事物管理器就是JDBC,连接池:POOLED

3、属性(Properties)

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

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

编写一个配置文件
dp.properties

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

在核心配置文件中引入

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

可以直接引入外部文件
可以在其中增加一些属性配置
如果两个文件有一个字段,优先使用外部配置文件

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

数据库中的字段
新建一个项目,拷贝之前的,测试实体类字段不一致的情况

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>

    <select id="getUserById" parameterType="int" resultMap="UserMap">
        select * from mybatis.user where id = #{id}
    </select>

ResultMap 元素是MyBatis中最重要强大的元素
ResultMap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。
ResultMap最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们。

日志

日志工厂

如果一个数据库操作出现了异常,我们需要排错。日志就是最好的助手
曾经:sout、debug
现在:日志工 厂
在这里插入图片描述
在Mybatis中具体使用哪一个日志实现,在设置中设定
STDOUT_LOGGING标准日志输出
在mybatis核心配置文件总,配置我们的日志

 <!--引入外部配置文件-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
Log4j

什么是Log4j?
Log4j是Apache的一个开源项目,通过Log4j,我们可以控制日志信息输出的目的地是控制台、文件、GUI组件
我们也可以控制每一条日志的输出
通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
通过一个配置文件来灵活地进行配置、而不需要修改应用代码
1、先导入Log4j的包

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
2、log4j.properties
log4j.rootLogger=DEBUG,console,file
#\u8F93\u51FA\u5230\u63A7\u5236\u53F0
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.Target=System.out
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/debug.log
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的使用,直接测试运行刚才的查询
简单使用

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

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

日志级别

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

为什么要分页?
减少数据的处理量

使用Limit分页
语法:select * from user limit startIndex,pageSize;
select * from user limit n; #[0,n-1]

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

3、测试

   @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",0);
        map.put("pageSize",2);
        List<User> userList = mapper.getUserByLimit(map);
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
RowRounds分页
分页插件

在这里插入图片描述

使用注解开发
面向接口编程

注解在接口上实现

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

需要再核心配置文件中绑定接口

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

测试
本质:反射机制实现
底层:动态代理

CRUD

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

关于@Param()注解

基本类型的参数或者String类型,需要加上
引用类型不需要加
如果只有一个基本类型的话,可以忽略,但是建议大家都加上
我们在SQL中引用的就是我们这里的@Param()中设定的属性名
#{} ${}的区别
在这里插入图片描述

动态SQL

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

IF
<select id="findActiveBlogWithTitleLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE state = ‘ACTIVE’
  <if test="title != null">
    AND title like #{title}
  </if>
</select>
choose(when,otherwise)
    <select id="queryBlogChoose" parameterType="map" resultMap="blog">
        select * from mybatis.blog where
        <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 * from mybatis.blog
<where>
	<if test="title" != null">
		title = #{title}
	</if>
	<if test="author != null">
		and author = #{author}
	</if>
</where>
    <update id="updateBlog" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="author != null">
                author = #{author}
            </if>
        </set>
        where id = #{id}
    </update>

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

SQL片段

有的时候,我们可能会将一些功能的部分抽取出来,方便复用
使用SQL标签抽取公共的部分

<sql id="if-title-author">
	<if test="title !=null">
		title = #{title}
	</if>
	<if test="author ! = null">
		and author = #{author}
	</if>
</sql>
在需要使用的地方使用Include标签引用即可
<select id ="queryBlogIF" parameterType ="map" resultType = "blog">
	select * from mybatis.blog
	<where>
		<include refid="if-title-author"></include>
	</where>
</select>

注意事项:
最好基于单表来定义SQL片段
不要存在where标签

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

缓存

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

1、什么是缓存(Cache)?
存在内存中的临时数据
将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
2、为什么使用缓存?
减少和数据库的交互次数,较少系统开销,提高系统效率。
3、什么样的数据能使用缓存?
经常查询并且不经常改变的数据。

Mybatis缓存

MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
	默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
	二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
	为了提高拓展性,Mybatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值