MyBatis基础(一)配置MyBatis以及小示例

MyBatis基础(一)配置MyBatis以及小示例

Mybatis简介

mybaits使用与dao层,原来的dao层使用的是jdbc(尽管重构了代码仍然有所冗余)。

Mybatis简介

MaBatis用于dao层的减冗余。让操作表像操作对象一样。

可以简化jdbc,实现数据的持久化,它是一个ORM(Object Relational Mapping)对象关系映射。可以把一个类与一张表建立映射关系,使操作表的元组就像操作对象一样使用。

ORM是一个概念,MyBatis只是其的一个实例。
在这里插入图片描述

Mybatis安装

使用maven依赖安装:

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

Mybatis使用

首先建立一张表

CREATE DATABASE IF NOT EXISTS user_mybatis

CREATE TABLE IF NOT EXISTS student(
	id INT(10) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(5),
	age INT(4),
	PRIMARY KEY(id)
)

然后建立一个实体类:

public class Student {
    private int id;
    private String name;
    private int age;
    
    public Student(){}
    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

配置pom文件:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>pers.qiu.MybatisStudy</groupId>
  <artifactId>MybatisStudyOne</artifactId>
  <version>1.0</version>

  <name>MybatisStudyOne</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

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

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.35</version>
    </dependency>
  </dependencies>
  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
    </resources>
      
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
  </build>

</project>

最后将表与类建立映射,mapper.xml中配置,mapper一般与实体类在一个文件中。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--这是一个sql映射的xml模板-->
<mapper namespace="org.mybatis.example.BlogMapper">
    <select id="selectPersonById" resultType="Blog" parameterType="int">
        select * from Blog where id = #{id}
    </select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org/DTD Mapper 3.0"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="pers.qiu.entity.StudentMapper">
    <select id="selectStudent" resultType="pers.qiu.entity.Student">
        select * from Blog where id = #{id}
    </select>
</mapper>
  • namespace:名称空间,就是你要映射的类。

  • id:接口方法名。

  • resultType:访问表后返回的类型。(原来使用jdbc是pstmt返回的一个ResultSet,然后从里面提取值创建一个对象后赋值,返回对象。现在是将类与表进行了映射后直接返回一个类对象即可)

  • parameterType:参数类型。(例如上述得到id)

  • #{}:这是前面函数调用时使用了简写参数名,那么使用这个就可以使用简写参数名了。

注意!这只是建立了实体类映射,但是mybatis还没有配呢!也就是还没和数据库中的表建立映射呢,前面只是类伸出了一条线,数据库还没有伸线呢!

配置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>
    <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://127.0.0.1:3306/user_mybatis?characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="111111"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置映射文件:用来配置sql语句和结果集类型等 -->
    <mappers>
        <mapper resource="pers/qiu/entity/StudentMapper.xml"/>
    </mappers>
</configuration>

从上述xml中可以看出,这个xml已经帮你弄好了数据库驱动以及连接,使用mapper.xml后就可以直接映射进行数据库的访问了。conf.xml相当于进行了连接配置,mapper.xml相当于进行了数据库访问。你需要在Java代码中操作只有用一个函数其中有参数信息即可实现数据的访问与持久化。

在Java中使用:

要注意Resources是org.apache.ibatis.io下的Resources。

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import pers.qiu.entity.Student;
import org.apache.ibatis.io.Resources;

public class TestMybatis{
    public static void main(String[] args){
        //将conf文件作为流对象(conf文件中有数据库连接信息)
        Reader reader = Resources.getResourceAsReader("conf.xml");
        //工厂根据reader的不同创建不同的对象,sessionFactory相当于数据库驱动等
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //session相当于数据库连接对象,打开连接
        SqlSession session = sessionFactory.openSession();
        //statement = "mapper文件地址+sql的ID"
        String statement = "pers.qiu.entity.StudentMapper.selectStudentById";
        //(sql地址,参数)
        Student student = session.selectOne(statement, 1);
        session.close();
    }
}

在这里插入图片描述

总结步骤:

  1. 配置conf、mapper的xml文件。

  2. 根据conf创建配置信息流对象reader。

  3. 根据reader创建session工厂,根据session工厂获取session连接对象。

  4. 根据mapper地址以及sql的ID,使用session执行sql语句。

  5. 关闭session对象。

重点就是conf、mapper这两个xml文件的配置。在其使用过程中可以明显看到比原来使用dao层有明显的低冗余、低耦合、高内聚。

置conf、mapper的xml文件。**

  1. 根据conf创建配置信息流对象reader。
  2. 根据reader创建session工厂,根据session工厂获取session连接对象。
  3. 根据mapper地址以及sql的ID,使用session执行sql语句。
  4. 关闭session对象。

重点就是conf、mapper这两个xml文件的配置。在其使用过程中可以明显看到比原来使用dao层有明显的低冗余、低耦合、高内聚。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值