Mybatis简单入门

1 mybatis简单介绍

MyBatis是一个ORM的数据库持久化框架。
Mybatis是一个支撑框架,它以映射sql语句orm方式来数据库持久化操作.
ORM:对象关系映射(Object Relational Mapping,简称ORM),是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术

1.1 ORM框架映射方式
Orm框架的操作数据库关系方式有很多种,常用的有两种:
1、Sql操作方式(对jdbc进行封装):
把SQL配置到配置文件中,通过不同SQL中完成对象实体和数据库关系相互转换的操作。(mybatis的实现方式)

2 完整映射:
直接映射的是对象实体和数据库关系映射。操作数据库关系,不用写SQL有框架自己生成。(JPA、Hibenate实现方式)

1.2 映射好处-原理:
1、以一定的映射方式,把实体模型和数据库关系的映射
2、ORM框架启动时加载这些映射和数据库配置文件
3、ORM通过对最原生jdbc的封装提供更加便利的操作API
4、Dao通过ORM提供的便捷API以对象的方式操作数据库关系。

mybatis简单入门

先创建一个简单的java项目
在这里插入图片描述
然后导入包
在这里插入图片描述
创建一个domain 数据库中记得建表

public class Product {
   
    private	Long id;
    //商品名称
    private String productName;
    //品牌
    private String brand;
    //供应商
    private String supplier;
    //零售价
    private Double salePrice;
    //进价
    private Double costPrice;
    //折扣价
    private Double cutoff;
    //商品分类编号
    private Long dir_id;

1 首先核心配置文件MyBatis-Config.xml 写在resources里面
不用专门找xml的文件新建,直接建个普通的file 加上xml就行了
①获取SqlSessionFactory
1 我们需要准备一个核心的Mybatis-config.xml文件
2 拿到SqlSessionFactory之前需要读取核心的xml配置文件
3 需要构造者(SqlSessionFactoryBuilder)来创建它
②映射文件准备
③通过SqlSessionFactory获取SqlSession执行映射SQL

<?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>

    <!--引入数据库的配置文件-->
    <properties resource="jdbc.properties"></properties>

    <!--配置别名   typeAliases:配置别名 注:别名不区别大小写 -->
      <typeAliases>
          <!-- type:类型   alias:别名-->
          <!--<typeAlias type="cn.itsource.domain.Product" alias="Product" />-->
          <!--为这个包下面的所有类取别名(就是类名)-->
          <package name="cn.itsource.mybatis.domain"/>
          <package name="cn.itsource.mybatis.query"/>
      </typeAliases>
    <!-- 环境们 (很多环境的意思) default:默认使用哪一个环境(必需对应一个环境的id) -->
    <environments default="development">
        <!--一个环境  id:为这个环境取唯一一个id名称 -->
        <environment id="development">
            <!--事务管理   type:JDBC(支持事务)/MANAGED(什么都不做) -->
            <transactionManager type="JDBC" />
            <!-- 数据源, 连接池  type(POOLED):MyBatis自带的连接池 -->
            <dataSource type="POOLED">
                <!-- 连接数据库的参数 -->
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    <!-- 这个mappers代表的是相应的ORM映射文件 -->
    <mappers>
        <!--引入(找到)写SQL的XML-->
        <mapper resource="cn/itsource/mybatis/dao/ProductMapper.xml" />
        <mapper resource="cn/itsource/mybatis/dao/EmployeeMapper.xml"/>
    </mappers>

</configuration>

①我们的映射文件(就是我们的mapper文件)一般情况下是和它对应的domain实体类在同一个层级
② 这个映射文件的名称一般叫做 XxxMapper.xml (Xxx代表的是实体类名称)
cn.itsource.mybatis.domain.Product
cn/itsource/mybatis/domain/ProductMapper.xml
③ namespace的名称为了确定唯一性,请大家根据我的要求取名
如我们有一个类:
cn.itsource.mybatis.domain.Product
那这里取名应该是:
cn.itsource.mybatis.domain.ProductMapper
④ 除了MyBatis支持的类型,其它的类型都通通使用全限定

整体结构:
在这里插入图片描述

建一个ProductMapper.xml 用来CRUD

<?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的主要功能就是写sql
	mapper:根
	namespace:命令空间 (用来确定唯一) 以前这个是可以不加的,现在必需加
     namespace的值,规则的:映射文件XxxMapper.xml所在的包+domain类名+Mapper
 -->
<mapper namespace="cn.itsource.mybatis.dao.ProductMapper">

    <!--
         根据查询条件获取数据
         There is no getter for property named 'id' in 'class java.lang.Long'
         #与$的区别:
            获取值的区别:
              $:拿到的是传过来的对象的某一个属性
              #:即可以单独拿对象,可以拿到传过来的对象的属性
            对SQL的影响
               #是使用预编译的方案(防sql注入,安全性更高,性能也会更强一些)
            结论:能用#都使用#(优先使用#)
    -->
    <select id="queryOne" parameterType="long" resultType="Product">
        select * from product where productName = #{productName}
    </select>
    <!--
        select : 这里面写查询语句
        id:用来确定这条sql语句的唯一
        以后我们确定唯一,也就是找sql语句 : namespace +.+ id
        例: cn.itsource.mybatis.domain.Product.getOne
        parameterType : 传入的参数类型  long:大Long  _long:小long (具体的对应请参见文档)
        resultType : 结果类型(第一条数据返回的对象类型) 自己的对象一定是全限定类名
     -->
    <select id="getOne" parameterType="long" resultType="cn.itsource.mybatis.domain.Product">
		select * from product where id = #{id}
	</select>
    <select id="getAll" resultType="cn.itsource.mybatis.domain.Product">
        select * from product
    </select>
    <!--
       添加一条数据
           useGeneratedKeys:是否要主键
           keyColumn="id":在数据库中名称叫id
           keyProperty="id":在类中也叫id
           主键会放到你传过来的对象中
   -->
    <insert id="save" parameterType="product" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
        insert into product
        (productName,dir_id,salePrice,supplier,brand,cutoff,costPrice) values
        (#{productName},#{dir_id},#{salePrice},#{supplier},#{brand},#{cutoff},#{costPrice})
    </insert>
    <!--修改一条数据-->
    <update id="update" parameterType="product">
        update product set
            productName=#{productName},
            dir_id=#{dir_id},
            salePrice=#{salePrice},
            supplier=#{supplier},
            brand=#{brand},
            cutoff=#{cutoff},
            costPrice=#{costPrice}
            where id=#{id}
    </update>
    <!-- 删除功能 -->
    <delete id="delete" parameterType="long">
        delete from product where id=#{id}
    </delete>

</mapper>

简单测试一下

  /**
     *
     * @throws Exception
     * 1  想办法搞到核心配置文件 mybatis‐config.xml
     * 2  获取到它的核心对象 SqlSession【相当于是咱们JPA中的EntityManager对象】 
     *       SqlSessionFactoryBuilder ‐> SqlSessionFactory ‐> SqlSession 
     * 3  SqlSession就可以CRUD.. 
     */
    @Test
    public void testGetOne() throws Exception{
   
        // 1  想办法搞到核心配置文件 mybatis‐config.xml
        Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
        // 2.1获到到SqlSessionFactory对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(reader);
        // 2.2获取到它的核心对象 SqlSession
        SqlSession session = factory.openSession();
        /**
         * String statement : 获取SQL的字符串 namespace+id
         * Object parameter : 参数传递
         */
        Product product = session.selectOne("cn.itsource.mybatis.dao.ProductMapper.getOne","1L");
        System.out.println(product);
        //关闭流
        session.close();
    }

    @Test
    public void testGetAll(<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值