mybatis 快速入门

pom依赖

  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.5</version>
  </dependency>

config.xml

创建 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>
<!-- 配置MyBatis运⾏行行环境 --> <environments default="development">
<environment id="development">
<!-- 配置JDBC事务管理理 -->
<transactionManager type="JDBC"></transactionManager> <!-- POOLED配置JDBC数据源连接池 -->
<dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver">
</property>
                <property name="url"
value="jdbc:mysql://localhost:3306/mybatis?
useUnicode=true&amp;characterEncoding=UTF-8"></property>
                <property name="username" value="root"></property>
                <property name="password" value="root"></property>
            </dataSource>
        </environment>
    </environments>
</configuration>

使用方式

使⽤用原⽣生接⼝
通过 Mapper 代理理实现⾃自定义接⼝(推荐使用)

1.通过 Mapper 代理实现⾃定义接⼝

自定义接⼝,定义相关业务方法。

1、自定义接⼝

 
package com.southwind.repository;
import com.southwind.entity.Account;
import java.util.List;
public interface AccountRepository {
    public int save(Account account);
    public int update(Account account);
    public int deleteById(long id);
    public List<Account> findAll();
    public Account findById(long id);
}

2.编写与方法相对应的 Mapper.xml

创建接⼝口对应的 Mapper.xml,定义接⼝口⽅方法对应的 SQL 语句句。
在这里插入图片描述

namespace 让,mapper.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.southwind.repository.AccountRepository">
    <insert id="save" parameterType="com.southwind.entity.Account">
        insert into t_account(username,password,age) values(#{username},#
{password},#{age})
    </insert>
    <update id="update" parameterType="com.southwind.entity.Account">
        update t_account set username = #{username},password = #{password},age
= #{age} where id = #{id}
    </update>
    <delete id="deleteById" parameterType="long">
        delete from t_account where id = #{id}
    </delete>
    <select id="findAll" resultType="com.southwind.entity.Account">
        select * from t_account
</select>
    <select id="findById" parameterType="long"
resultType="com.southwind.entity.Account">
        select * from t_account where id = #{id}
    </select>
</mapper>

mapper.xml 和接口方法中的关系
在这里插入图片描述

3、在 config.xml 中注册 AccountRepository.xml

告诉mybatis mapper.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>
    
    <settings>
        <!-- 打印SQL-->
        <setting name="logImpl" value="STDOUT_LOGGING" />
        <!-- 开启延迟加载 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 开启二级缓存 -->
        <setting name="cacheEnabled" value="true"/>
    </settings>
    
    <!-- 配置MyBatis运行环境 -->
    <environments default="development">
        <environment id="development">
            <!-- 配置JDBC事务管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- POOLED配置JDBC数据源连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
                <property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8"></property>
                <property name="username" value="root"></property>
                <property name="password" value="root"></property>
            </dataSource>
        </environment>
    </environments>

    <!-- 注册AccountMapper.xml -->
    <mappers>
        <mapper resource="com/southwind/mapper/AccountMapper.xml"></mapper>
        <mapper resource="com/southwind/repository/AccountRepository.xml"></mapper>
        <mapper resource="com/southwind/repository/StudentRepository.xml"></mapper>
        <mapper resource="com/southwind/repository/ClassesRepository.xml"/>
        <mapper resource="com/southwind/repository/CustomerRepository.xml"/>
        <mapper resource="com/southwind/repository/GoodsRepository.xml"/>
    </mappers>

</configuration>

4、调⽤用接⼝口的代理理对象完成相关的业务操作

在这里插入图片描述

package com.southwind.test;

import com.southwind.entity.Account;
import com.southwind.repository.AccountRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

public class Test2 {
    public static void main(String[] args) {
        InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取实现接口的代理对象
        AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);
      //  添加对象
        Account account = new Account(3L,"王五","111111",24);
        int result = accountRepository.save(account);
        sqlSession.commit();
       // 查询全部对象
        List<Account> list = accountRepository.findAll();
        for (Account account:list){
            System.out.println(account);
        }
        sqlSession.close();
       // 通过id查询对象
        Account account = accountRepository.findById(3L);
        System.out.println(account);
        sqlSession.close();
      //  修改对象
        Account account = accountRepository.findById(3L);
        account.setUsername("小明");
        account.setPassword("000");
        account.setAge(18);
        int result = accountRepository.update(account);
        sqlSession.commit();
        System.out.println(result);
        sqlSession.close();
       // 通过id删除对象
        int result = accountRepository.deleteById(3L);
        System.out.println(result);
        sqlSession.commit();
        System.out.println(accountRepository.findByName("张三"));
        Long id = Long.parseLong("1");
        System.out.println(accountRepository.findById2(id));
        System.out.println(accountRepository.findByNameAndAge("张三",22));
        System.out.println(accountRepository.count());
        System.out.println(accountRepository.count2());
        System.out.println(accountRepository.findNameById(1L));
        sqlSession.close();
    }
}

2.Mapper.xml详解

  • statement 标签:select、update、delete、insert 分别对应查询、修改、删除、添加操作。
  • parameterType:参数数据类型
  • parameterType:参数数据类型

1、基本数据类型,通过 id 查询 Account
在这里插入图片描述

resultType:结果类型

在这里插入图片描述
在这里插入图片描述

Mybatis执行sql(insert、update、delete)返回值

insert: 插入n条记录,返回影响行数n。(n>=1,n为0时实际为插入失败)

update:更新n条记录,返回影响行数n。(n>=0)

delete: 删除n条记录,返回影响行数n。(n>=0)

3.MyBatis 缓存

在这里插入图片描述

mybatis不支持分布式缓存

mybatis本身来说是无法实现分布式缓存的,所以要与分布式缓存框架进行整合。
Mybatis-Redis二级缓存分布式实现
mybatis框架下整合分布式缓存ehcache
在这里插入图片描述

4.MyBatis 动态 SQL

MyBatis 动态 SQL: 动态的拼接sql, 根据不同的情况拼接出不同的sql

使⽤用动态 SQL 可简化代码的开发,减少开发者的⼯工作量量,程序可以⾃自动根据业务参数来决定 SQL 的组
成。

满足标签的判断,标签包裹的内容保留下来拼接sql语句

if 标签

if 标签可以⾃动根据表达式的结果来决定是否将对应的语句添加到 SQL 中,如果条件不成⽴则不不添加, 如果条件成立则添加。

<select id="findByAccount" parameterType="com.southwind.entity.Account"
 resultType="com.southwind.entity.Account">
   select * from t_account where
     <if test="id!=0">
         id = #{id}
     </if>
     <if test="username!=null">
         and username = #{username}
     </if>
     <if test="password!=null">
         and password = #{password}
     </if>
     <if test="age!=0">
         and age = #{age}
     </if>
</select>

在这里插入图片描述

where 标签

where 标签可以⾃自动判断是否要删除语句句块中的 and 关键字,如果检测到 where 直接跟 and 拼接,则 ⾃自动删除 and,通常情况下 if 和 where 结合起来使⽤用。

在这里插入图片描述

<select id="findByAccount" parameterType="com.southwind.entity.Account"
 resultType="com.southwind.entity.Account">
     select * from t_account
     <where>
         <if test="id!=0">
             id = #{id}
         </if>
         <if test="username!=null">
             and username = #{username}
         </if>
         <if test="password!=null">
             and password = #{password}
         </if>
         <if test="age!=0">
             and age = #{age}
         </if>
     </where>
 </select>

choose 、when 标签

<select id="findByAccount" parameterType="com.southwind.entity.Account"
 resultType="com.southwind.entity.Account">
     select * from t_account
     <where>
         <choose>
             <when test="id!=0">
                  id = #{id}
             </when>
             <when test="username!=null">
                 username = #{username}
             </when>
             <when test="password!=null">
                 password = #{password}
             </when>
             <when test="age!=0">
                 age = #{age}
             </when>
         </choose>
     </where>
 </select>

trim 标签

trim 标签中的 prefix 和 suffix 属性会被⽤用于⽣生成实际的 SQL 语句句,会和标签内部的语句句进⾏行行拼接,如 果语句句前后出现了了 prefixOverrides 或者 suffixOverrides 属性中指定的值,MyBatis 框架会⾃自动将其删 除。

<select id="findByAccount" parameterType="com.southwind.entity.Account"
 resultType="com.southwind.entity.Account">
     select * from t_account
     <trim prefix="where" prefixOverrides="and">
         <if test="id!=0">
             id = #{id}
         </if>
         <if test="username!=null">
             and username = #{username}
         </if>
         <if test="password!=null">
             and password = #{password}
         </if>
         <if test="age!=0">
             and age = #{age}
         </if>
     </trim>
 </select>

set 标签

set 标签⽤用于 update 操作,会⾃自动根据参数选择⽣生成 SQL 语句句。

<update id="update" parameterType="com.southwind.entity.Account">
     update t_account
     <set>
         <if test="username!=null">
  username = #{username},
            </if>
         <if test="password!=null">
             password = #{password},
         </if>
         <if test="age!=0">
             age = #{age}
</if> </set>
     where id = #{id}
 </update>

foreach 标签

foreach 标签可以迭代⽣生成⼀一系列列值,这个标签主要⽤用于 SQL 的 in 语句句。

<select id="findByIds" parameterType="com.southwind.entity.Account"
 resultType="com.southwind.entity.Account">
       select * from t_account
       <where>
           <foreach collection="ids" open="id in (" close=")" item="id"
 separator=",">
               #{id}
           </foreach>
       </where>
 </select>
 

在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值