Mybatis的Demo使用(详细创建项目的步骤,注解形式和非注解形式实现)

先来了解一下三层架构

界面层(视图层):接收用户的请求,调用service,显示请求的处理结果的。对应的包叫做Controller。

业务逻辑层,处理业务逻辑,使用算法处理数据,吧数据返回给界面层,对应的包是service。

持久层(数据库访问层):访问数据库,或者读取文件,访问网络。对应的包是dao。

想象一下一个网页里面的学生信息,他是怎样来从数据库中获取出来,显示到网页中来的?

本篇主要介绍对持久层(数据库访问层)的一种框架:Mybatis  。即了解怎样从数据库中拿取数据。

现在来创建项目,实现一个通过id从数据库中拿取到学生信息的过程。

先选择新建一个项目。

 选择Maven,不要选择模板,直接下一步。

写清楚路径和项目名称 

 项目名称和项目路径

 ok。项目创建成功。

接着将java包右击设置成Sources Root(图标是蓝色的包)

 resources包设置成Resources Root

如果创建出来的没有下面包,请自行创建成如下目录结构

目录创建好之后,来配置一下需要的依赖

复制如下代码到pom.xml中

<?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">
    <parent>
        <artifactId>FrameDemo</artifactId>
        <groupId>com.che</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>MybatisDemo</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
            <scope>test</scope>
        </dependency>

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.6</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
        </dependencies>



</project>

在recources包路径下创建一个全局配置文件 mybatis-config.xml

里面包含对数据源的配置和对接口的映射文件(如果使用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>
    <!--配置数据源-->
    <environments default="development">
        <!--环境配置,可以配置多个环境-->
        <environment id="development">
            <!--事务管理器 使用JDBC的事务管理器-->
            <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/che"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!--每个方法对应的映射文件引入,都需要在这里配置,才能找到-->
    <mappers>
    <!--引入配置文件使用resource,引入接口用class-->
    <mapper resource="mapper/StudentDao.xml"></mapper>   
<!--注意:在使用非注解形式配置时,把不需要的配置文件的引入都屏蔽掉!!!-->
<!--<mapper class="com.che.dao.StudentDao"/>-->

    </mappers>

</configuration>

 下来在che目录下创建pojo包,里面放置一个Student类 ,该类里面有学生的基本属性,id,name,age,sex信息和getter,setter方法。

package com.che.pojo;

public class Student {
    private int id;//学号
    private String name;//姓名
    private int age;//年龄
    private String sex;//性别

    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;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
 public Student() {
    }
    public Student(int id, String name, int age, String sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
}

在che包下创建一个dao包,放置一个StudentDao接口

package com.che.dao;

import com.che.pojo.Student;

public interface StudentDao {
    //根据id查找对应学生信息
    public Student selectStudentById(Integer id);
}

下面有两种方法分别来配置方法:

使用xml形式配置方法:在resources文件下创建mapper包,里面放置所有的和接口对应的配置文件(最好配置文件的名称与接口名称相同),所以StudentDao.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.che.dao.StudentDao">

    <!--
    id:statementID,在同一个命名空间下具有唯一性,一般是对应接口中方法
    parameterType:表示参数类型
    resultType:指定返回类型

    #{XXX}:表示占位符  ?
    -->
    <select id="selectStudentById" parameterType="Integer" resultType="com.che.pojo.Student">
        select * from student where id = #{id}
    </select>


</mapper>

配置好之后需要将其在全局配置文件mybatis-config.xml中配置一下(上面的mybatis-config.xml文件中已经写入这个代码)

    <!--映射文件引入 使用resource指明配置文件的路径-->
    <mappers>
            <mapper resource="mapper/StudentDao.xml"></mapper>
    </mappers>

最后在test目录下测试该方法:

package com.che;

import com.che.pojo.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;

import java.io.IOException;
import java.io.InputStream;

public class StudentDaoTest {
    @Test
    public void selectStudentById() throws IOException {
        //给定全局配置文件
        String config = "mybatis-config.xml";
        //通过配置文件获取资源流
        InputStream stream = Resources.getResourceAsStream(config);

        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream);
        //通过会话工厂创建会话
         SqlSession session = factory.openSession();
        // 给定方法 是StudentDao.xml中的命名空间(对应的接口的全路径)+ . +方法名称
        String sqlId = "com.che.dao.StudentDao.selectStudentById";
        //执行方法 传进去所需要的参数id
        Student student = session.selectOne(sqlId,1);
        System.out.println("学生信息是:"+student);
    }

}

得到的测试结果为:

和数据库中的数据比较,一致! 操作成功!

总结:

创建项目

配置pom.xml

配置全局配置文件 mybatis-config.xml

创建Student的pojo类

创建Dao接口

创建Dao配置文件(别忘了在全局配置文件中引入该映射文件)

编写测试Test类

对应的目录结构如图。

  

第二种用注解形式配置方法:

在Student类中加入insertStudent 方法,插入学生数据到数据库中

首先在Student类中添加一下构造方法

    public Student(int id, String name, int age, String sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

在StudentDao接口中添加如下方法:

@Insert("insert into student(id,name,age,sex) values(#{id},#{name},#{age},#{sex})")
     void insertStudent(Student student);

在全局配置文件中引入(让它知道该去哪里加载什么方法)

  <mappers>
        <!--<mapper resource="mapper/StudentDao.xml"></mapper>-->

        <mapper class="com.che.dao.StudentDao"/>
    </mappers>

接着在Test测试类中添加测试方法

    @Test
    public void insertStudent() throws IOException {
        //给定全局配置文件
        String config = "mybatis-config.xml";
        //通过配置文件获取资源流
        InputStream stream = Resources.getResourceAsStream(config);

        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream);
        //通过会话工厂创建会话
        SqlSession session = factory.openSession();
        //利用反射机制,获取Student对象信息
        StudentDao mapper = session.getMapper(StudentDao.class);
        //调用添加学生信息方法
        mapper.insertStudent(new Student(9,"车车",20,"女"));
        System.out.println("学生信息是否传入");
        session.commit();
}

最后给出运行结果

 对比数据库数据

添加成功! 

注解形式配置总结:

创建项目

配置pom.xml

配置全局配置文件 mybatis-config.xml

创建Student的pojo类

创建Dao接口

在全局配置文件中引入该java类

编写测试Test类

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值