快速入门Mybatis

MyBatis是apache的一个开源项目iBatis,是实现了数据持久层的一个开源框架。是一个ORMapping:对象关系映射(对象就是面向对象,关系就是关系型数据库)如java到Mysql的映射,开发者可以用面向对象的思想开管理数据库。
简单理解就是对JDBC进行封装。
优点:

  1. 与JDBC相比减少了50%以上的代码量。
  2. 是最简单的持久化框架,小巧并且简单容易学。
  3. 相当灵活,不对对应用程序或者数据库的现有设计强加任何影响,SQL写在XML里,从程序代码中彻底分离,降低耦合度,便于统一管理和优化,并且可以重用。
  4. 提供XML标签,支持编写动态SQL语句。
  5. 提供映射标签,支持对象与数据库的ORM字段关系映射。

缺点:

  1. SQL语句的编写工作量比较大,尤其是字段多、关联表多时,更是如此,对开发人员编写SQL语句的功底有一定要求。
  2. SQL语句依赖于数据库,导致数据库移植性差,不能随意更换数据库。

Mybatis核心接口和类
SqlSessionFactoryBuilder-[builder()]->SqlSessionFactory
-[openSession()]->SqlSession。
MyBatis的开发方式
1、使用原生接口
2、Mapper代理实现自定义接口

如何使用

  • 新建Maven工程,pom.xm
<dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-oscache</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>sql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
    </dependencies>
  • 新建数据表(本人在DataGrip中)
use mybatis;
create table t_account(
    id int primary key auto_increment,
    username varchar(11),
    password varchar(11),
    age int
)
  • 根据数据表新建实体类
package com.wanaei.entity;

import lombok.Data;

@Data
public class Account {
   private long id;
   private String username;
   private String password;
   private int age;
}
  • 创建MyBatis的配置文件(放进src.main.resources文件下)
 <?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 xmlns="$LOCAL_SCHEMA$">
    <!--配置MyBatis运行环境 -->
    <environments default="development">
        <enviroment id="development">
            <!-- 配置JDBC事物管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- POOLED配置JDBC数据源连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc"></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>

使用原生接口
1、Mybatis框架需要开发者自定义sql语句,写在Mapper.xml文件中,实际开发中,会为每个实体类创建对应的Mapper.xml,定义管理该对象数据的SQL
2、在全局配置文件config.xml中注册AccountMapper.xml

<configuration xmlns="$LOCAL_SCHEMA$">
    <!--配置MyBatis运行环境 -->
    <environments default="development">
        <enviroment id="development">
            <!-- 配置JDBC事物管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- POOLED配置JDBC数据源连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc"></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>
        </enviroment>
    </environments>
    <!-- 2注册AccountMapper.xml-->
    <mappers>
        <mapper resource="com/wanaei/mapper/AccountMapper.xml"></mapper>
    </mappers>
</configuration>

3、调用Mybatis的原生接口执行[添加等]操作。

import com.wanaei.entity.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Test {
    public static void main(String[] args) {
        //加载MyBatis的配置文件
        InputStream inputStream =Test.class.getClassLoader().getResourceAsStream("config.xml");
        SqlSessionFactorybuilder sqlSessionFactorybuilder = new SqlSessionFactorybuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactorybuilder.build(inputStream);//通过配置文件配置工厂
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String statement = "com.wanaei.mapper.AccountMapper.save";
        Account account = new Account(1L,"张三","root",12);
        sqlSession.insert(statement);
        sqlSession.commit();
    }
}

使用Mapper代理实现自定义接口

  • 自定义接口,定义相关的业务方法

  • 编写与方法相对应的Mapper.xml
    1、自定义接口

package com.wanaei.repository;

import com.wanaei.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,定义接口方法对应的SQL语句。
statement标签可根据SQL执行的业务选择insert、delete、update、select。
MyBatis框架会根据规则自动创建接口实现类的代理对象。
规则:

  • Mapper.xml中namespace为接口的全类名。
  • Mapper.xml中的statement的id为接口中对应的方法名。
  • Mapper.xml中的statement的parameterType和接口中对应方法的参数类型一致。
  • Mapper.xml中的statement的resultType和接口中对应方法的返回值类型一致。
<?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.wanaei.repository.AccountRepository">
    <insert id="save" parameterType="com.wanaei.entity.Account">
        insert into t_account(username,password,age) value(#{username},#{password},#{age})
    </insert>
    <update id="update" parameterType="com.wanaei.entity.Account">
        update t_account set username=#{username},password=#{password},age=#{age} where id=#{id}
    </update>
    <delete id="deleteById" parameterType="com.wanaei.entity.Account">
        delete from t_account where id = #{id}
    </delete>
    <select id="findAll" resultType="com.wanaei.entity.Account">
        select * from t_account
    </select>
    <select id="findById" parameterType="long" resultType="com.wanaei.entity.Account">
        select * from t_account where id=#{id}
    </select>
</mapper>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不想当个程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值