Mybatis的入门(idea)


一、Mybatis入门(在maven中操作)

1.创建数据库表

2.导入依赖

 <!--mybatis 依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

        <!--mysql 驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

3.导入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>
    <!--起别名-->
    <typeAliases>
        <package name="com.itheima.pojo"></package>
    </typeAliases>
    <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:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--映射mapper的xml文件,找写sql 的xml文件-->
    <mappers>
        <!--package 扫描mapper接口包,在利用映射找到mapper.xml文件
            映射咋找呢?
            是利用mapper接口的类名称和xml文件的名称一致,才会在complie之后,在target包中,二个文件存在在同一个目录下
            
            <mapper resource=""/>
            直接扫描mapper.xml文件-->
        <package name="com.itheima.mapper"/>
    </mappers>
</configuration>

4.编写mapper.xml 配置文件 —>(编写sql脚本)

<?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">
<!--创建该文件的时候,要注意,在resources目录下要用/代替.创建多层目录-->
<!--接口的全路径-->

<mapper namespace="com.itheima.mapper.BrandMapper" >
    <!--    resultMap 完成不一致的属性名和列名的映射
     id:完成主键字段的映射
              column:表的列名
             property:实体类的属性名
     result:完成一般字段的映射
       column:表的列名
         property:实体类的属性名-->
    <resultMap id="brandResultMap" type="Brand">
        <id column="id" property="id"/>
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
        <result column="ordered" property="ordered"/>
        <result column="description" property="description"/>
        <result column="status" property="status"/>
    </resultMap>
    <update id="updateBrandById" parameterType="int" keyProperty="int">
        update tb_brand set status = #{status} where id=#{id}
    </update>
     <!--id是sql语句的唯一标识,接口中的方法名-->
    <!--resultType:返回值类型-->
    <!--parameterType:传参的类型-->
    <select id="findBrand" resultMap="brandResultMap">
        select * from tb_brand
    </select>
</mapper>

figs:
可以在idea中下载个规范插件—MybatisX ,下载成功之后可以检查xml中的id是否存在于接口中

5.编码实现
数据库准备:

-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand
(
    -- id 主键
    id           int primary key auto_increment,
    -- 品牌名称
    brand_name   varchar(20),
    -- 企业名称
    company_name varchar(20),
    -- 排序字段
    ordered      int,
    -- 描述信息
    description  varchar(100),
    -- 状态:0:禁用  1:启用
    status       int
);
-- 添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1);

pojo类:

Brand类

package com.itheima.pojo;

import lombok.Data;

/**
 * @author
 * @action
 */

public class Brand {
    private int id;
    private String brandName;
    private String companyName;
    private int ordered;
    private String description;
    private int status;

    @Override
    public String toString() {
        return "Brand{" +
                "id=" + id +
                ", brandName='" + brandName + '\'' +
                ", companyName='" + companyName + '\'' +
                ", ordered=" + ordered +
                ", description='" + description + '\'' +
                ", status=" + status +
                '}';
    }

    public Brand(int id, String brandName, String companyName, int ordered, String description, int status) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.ordered = ordered;
        this.description = description;
        this.status = status;
    }

    public Brand() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBrandName() {
        return brandName;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public int getOrdered() {
        return ordered;
    }

    public void setOrdered(int ordered) {
        this.ordered = ordered;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }
}

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>
    <!--起别名-->
    <typeAliases>
        <package name="com.itheima.pojo"></package>
    </typeAliases>
    <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:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--映射mapper的xml文件,找写sql 的xml文件-->
    <mappers>
        <!--扫描mapper包-->
        <package name="com.itheima.mapper"/>
    </mappers>
</configuration>

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">
<!--创建该文件的时候,要注意,在resources目录下要用/代替.创建多层目录-->
<!--接口的全路径-->

<mapper namespace="com.itheima.mapper.BrandMapper" >
    <!--    resultMap 完成不一致的属性名和列名的映射
     id:完成主键字段的映射
              column:表的列名
             property:实体类的属性名
     result:完成一般字段的映射
       column:表的列名
         property:实体类的属性名-->
    <resultMap id="brandResultMap" type="Brand">
        <id column="id" property="id"/>
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
        <result column="ordered" property="ordered"/>
        <result column="description" property="description"/>
        <result column="status" property="status"/>
    </resultMap>
    <update id="updateBrandById" parameterType="int" keyProperty="int">
        update tb_brand set status = #{status} where id=#{id}
    </update>
    <select id="findBrand" resultMap="brandResultMap">
        select * from tb_brand
    </select>

</mapper>

mapper的接口类

package com.itheima.mapper;

import com.itheima.pojo.Brand;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @author
 * @action
 */
public interface BrandMapper {
    /**
     * find all brand
     * @return List<Brand>
     */
    List<Brand> findBrand();

    /***
     * update status by id
     * @param id
     * @param status
     * @return
     */
    int updateBrandById(@Param("id") int id,@Param("status") int status);
}

使用单元测试进行测试
在使用单元测试之前要先在pom.xml中引入junit的坐标依赖

  <!--junit 单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
package com.itheima;

import com.itheima.mapper.BrandMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Brand;
import com.itheima.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

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

public class mapperTest {
    @Test
    public  void testMapper() throws Exception {
        InputStream resource = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper  mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brand = mapper.findBrand();
        for (Brand brand1 : brand) {
            System.out.println(brand1);
        }
        int i = mapper.updateBrandById(2,1);
        System.out.println(i);
        sqlSession.commit();
        //5. 释放资源
        sqlSession.close();
        /*User userById = mapper.findUserById(1);
        System.out.println(userById);*/
    }
}

结果:
在这里插入图片描述

二、乱乱的整理知识点

1、pom.xml配置文件要导入相应的坐标索引
2、mybatis-config.xml配置文件中的标签是设置的是所要扫描的mapper.xml文件(该文件是存在于resources目录下)
3、想要将mapper.xml文件与mapper接口映射成功,需要在resources目录下建立与mapper接口相应的目录层级,在resources目录下建立目录层级,要用/隔开,不能使用 . 如:com/textcast/mapper
4、在mapper接口与mapper.xml映射成功之后,会在target目录层级中二个出现在一起,如:
在这里插入图片描述
5、在pom.xml文件中dependency标签中的scope标签代表坐标的依赖范围
如Junit坐标依赖

 <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
依赖范围编译classpath测试classpath运行classpath例子
compileYYYlogback
test-Y-Junit
providedYY-servlet-api
runtime-YYjdbc驱动
systemYY-存储在本地的jar包

6、使用mybatis代理的要求
定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下
设置SQL映射文件的namespace属性为Mapper接口全限定名
在 Mapper 接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致

7、可以在mybatis-config 中设置别名,注意标签要放在environments标签的上面,位置放不对会报错

<!--全局别名,比如在mapper.xml中就可以省略前面的包名,直接写实体类名-->
<typeAliases>
        <package name="com.itheima.pojo"></package>
 </typeAliases>

三、JUnit单元测试

1、在pom.xml中导入坐标索引

<!--junit 单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

2、JUnit的三个注释

  • @Test
    只能放在无参数、无返回值、非静态的方法上
  • @Before
    在执行被@Test注释的方法之前执行
  • @After
    在执行完@Test注释的方法之后执行
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值