MyBatis

MyBatis

1.什么是MyBatis

MyBatis 本是 apache 的一个开源项目 ,前身iBatis。是一个基于java的持久层框架,它支持定制化 SQL、存储过程以及高级映射,是一个半自动化的ORM框架。

2.MyBatis环境搭建
1. 导入jar包

MyBatis的官方网站可以下载MyBatis.jar的最新版本
使用Maven构建项目只需要将下面的 dependency 代码置于 pom.xml 文件中

<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>x.x.x</version>
</dependency>
2.创建MyBatis核心配置文件configuration.xml

MyBatis核心配置文件主要用于配置数据库链接和MyBatis运行时所需要的各种特性,包含了设置和影响MyBatis行为的属性,我们一般将此文件命名为mybatis-config.xml。

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <properties resource="database.properties"/>
    <typeAliases >
        <typeAlias  alias="user" type="com.pojo.User"></typeAlias>
    </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 resource="com/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

mybatis-config.xml文件的常用的几个元素的作用

  1. configuration :配置文件的根元素节点‘
  2. properties:通过resources属性从外部指定properties属性文件(database.properties)该属性文件描述了数据库连接的相关配置(数据库驱动,连接数据库的url,数据库用户名,数据库密码)
  3. settings:设置mybatis运行中的一些行为
  4. environments:配置MyBatis的多套运行环境,将Sql映射到多个不同的数据库上,该元素下可配置多个environment子元素节点,但是必须指定一个默认的运行环境(通过default指定)
  5. environment:配置MyBatis的一套运行环境
  6. mappers:映射sql文件,整个项目可以有一个或多个SQL映射文件
  7. mapper:mappers的子元素节点,具体指定SQL映射文件的路径。
3.创建持久化类(POJO)和SQL映射文件

POJO类可以很简单的理解为符合javaBean规范的实体类,访问属性必须通过对应的getter和setter方法。
SQL映射文件为xml文件

<?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.mapper.ElectronicMapeer">
    <select id="selectList" resultType="com.pojo.Electronic">
      SELECT * FROM `kehou`
    </select>
</mapper>

其个元素的含义如下:

  1. mapper:映射文件的根元素节点,只有一个属性namespace
    namespace:用于区分不同的mapper,全局唯一
  2. select:表示查询语句,是MyBatis最常用的元素之一
    id属性:改命名空间下的唯一标识。
    resultType属性: 表示SQl语句返回值类型
4.创建测试类

进行功能测试

5.MyBatis的基本要素——核心对象
  1. 三个基本要素
    核心接口和类。
    MyBatis核心配置文件(mybatis-config.xml)
    SQL映射文件(mapper.xml)
  2. 核心接口和类
    每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为中心的。
    SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而
    SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration
    的实例构建出 SqlSessionFactory 的实例。
  3. 从 XML 文件中构建 SqlSessionFactory 的实例
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStr
eam);


4. 从 SqlSessionFactory 中获取 SqlSession

```java
SqlSession session = sqlSessionFactory.openSession();
  1. 通过SqlSession 实例来直接执行已映射的 SQL 语句
3.使用MyBatis实现条件查询
1. SQL映射文件

cache – 给定命名空间的缓存配置。
cache-ref – 其他命名空间缓存配置的引用。
resultMap – 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载
对象。
parameterMap 老式风格的参数映射。内联参数是首选,这个元素可能在
将来被移除,这里不会记录。

sql – 可被其他语句引用的可重用语句块。
insert – 映射插入语句
update – 映射更新语句
delete – 映射删除语句
select – 映射查询语句

2. select 查询
<select id="selectPerson" parameterType="int" resultType="hashmap">
SELECT * FROM PERSON WHERE ID = #{id}
</select>

参数符号:#{id}
使用@Param注解实现多参数入参

public void selectPerson(@Param"id")Integer id)
  1. id: 在命名空间中唯一的标识符,可以被用来引用这条语句。
  2. parameterType 将会传入这条语句的参数类的完全限定名或别名
  3. resultType 从这条语句中返回的期望类型的类的完全限定名或别名。
  4. resultMap 外部 resultMap 的命名引用
    resultType 或 resultMap,不能同时使用。
3. insert, update 和 delete
<insert id="insertAuthor">
insert into Author (id,username,password,email,bio)
values (#{id},#{username},#{password},#{email},#{bio})
</insert>

<update id="updateAuthor">
update Author set
username = #{username},
password = #{password},
email = #{email},
bio = #{bio}
where id = #{id}
</update>

<delete id="deleteAuthor">
delete from Author where id = #{id}
</delete>
4.使用resultMap实现高级结果映射
  1. resultMap的基本配置项
    属性:
    id:resultMap的唯一标识
    type:表示该resultMap的映射结果类型(通常是java实体类)
  2. association
    映射到JavaBean的某个“复杂类型” 属性
  3. collection
    映射到JavaBean的某个“复杂类型” 属性,属性为一个集合列表
4.动态SQL
1. if

判断条件是否为空

<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
2. choose (when, otherwise)

otherwise为默认的条件

<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
3.where

where条件会自动去掉第一个条件上的and 或 or

<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="title != null">
AND title like #{title}
</if>
</where>
</select>

4. trim (where, set)

可以代替where ,set

<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
<trim prefix="SET" suffixOverrides=",">
...
</trim>
5. foreach

对一个集合进行遍历

<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
6.MyBatis分页

导入jar包

 <!-- pagehelper -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.10</version>
    </dependency>
    <!-- jsqlparser -->
    <dependency>
      <groupId>com.github.jsqlparser</groupId>
      <artifactId>jsqlparser</artifactId>
      <version>3.0</version>
    </dependency>

在调用方法前加上代码,和调用方法的代码紧邻

 PageHelper.startPage(1, 2, true);

第一个参数,第几页,第二个参数显示几条数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值