创建一个user类,用JDBC(可以使用DBUtils)和Mybatis分别完成需求

1.题目

创建一个user类,用JDBC(可以使用DBUtils)和Mybatis分别完成以下需求
a, 根据名字查询用户
b, 查询所有用户
c, 根据id删除用户
d, 修改用户名字

2.JDBC(DBUtils)

3.Mybatis

3.1 结构

在这里插入图片描述

3.2 pom.xml(maven配置文件)

此文件主要用于简化导包流程,申明在main/java/dao中配置文件能被读取的作用。
在这里插入图片描述

<?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>com.gy</groupId>
    <artifactId>mybatis_work</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--Mybatis导包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.4</version>
        </dependency>

        <dependency>
            <!--数据库连接-->
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <!-- 两个* 表示通配 *和我们的 _ 占位比较类似-->
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

3.2 StudentMapper(一个接口)

package dao;
public interface StudentMapper {
    
    

}

3.3 StudentMapper.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="dao.StudentMapper">


    <!--b, 查询所有用户-->

    <select id="selectAll" resultType="Student.Student">
        select * from student;
    </select>


    <!--a, 根据名字查询用户-->
    <select id="selectOneByName" resultType="Student.Student">
       select id,name,age,sex,address,math,english from student where name = #{
    
    name}
    </select>

    <!--c, 根据id删除用户-->



    <delete id="deleteStudentById">
        delete from student where id = #{
    
    id}
    </delete>

    <!--d, 修改用户名字-->
    <update id="updateName">
        update student set name = #{
    
    name}
    </update>

</mapper>

3.4 Student.java(bean用于接收数据)

package Student;

public class Student {
    
    

    private Integer id;
    private String name;
    private Integer age;
    private String sex;
    private String address;
    private Integer math;
    private Integer english;

    public Student() {
    
    
    }



    public Integer getId() {
    
    
        return id;
    }

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

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public Integer getAge() {
    
    
        return age;
    }

    public void setAge(Integer age) {
    
    
        this.age = age;
    }

    public String getSex() {
    
    
        return sex;
    }

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

    public String getAddress() {
    
    
        return address;
    }

    public void setAddress(String address) {
    
    
        this.address = address;
    }

    public Integer getMath() {
    
    
        return math;
    }

    public void setMath(Integer math) {
    
    
        this.math = math;
    }

    public Integer getEnglish() {
    
    
        return english;
    }

    public void setEnglish(Integer english) {
    
    
        this.english = english;
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                ", math=" + math +
                ", english=" + english +
                '}';
    }

}

3.5 mybatis-config.xml(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">
<!--这个是Mybatis的主配置文件 上面的dtd 文件定义了这个xml文件中的标签的名字,出现的位置,顺序-->
<!-- 这个configuration其实就是这个配置文件的头,表示这个配置文件的开始 -->
<configuration>

    <!--environments 这个表示我们的数据源的环境-->
    <environments default="dev">

        <!--id 表示环境的名字-->
        <environment id="dev">
            <!--事务管理器 表示数据库事务交给谁去管理 , Type=JDBC表示交给JDBC去管理-->
            <transactionManager type="JDBC"/>

            <!--数据源(连接池)-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/testdb1?characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>

    </environments>

    <!--这个配置的是表示我们Mybatis需要把哪个Mapper加载进来,找到mapper.xml文件的位置-->
    <mappers>
        <!--<mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
        <mapper resource="dao/StudentMapper.xml"/>
    </mappers>

</configuration>

3.6 MybatisTest.java(Mybatis测试类)

3.6.1 知识准备

SqlSessionFactoryBuilder:利用XML或者Java编码获得资源来构建SqlSessionFactory。通过它可以构建过个SqlSessionFactory。它的作用就是一个构建器,一旦构建了SqlSessionFactory,它的作用也就消失了。
SqlSessionFactoryBuilder的在Mybatis的整个流程中的作用如下图:

在这里插入图片描述
SqlSessionFactory:简单的理解就是创建SqlSession实例的工厂。所有的MyBatis应用都是以SqlSessionFactory实例为中心,SqlSessionFactory的实例可以通过SqlSessionFactoryBuilder对象来获取。有了它以后,顾名思义,就可以通过SqlSession提供的openSession()方法来获取SqlSession实例。

SqlSession
一、什么是SqlSession呢?
SqlSession是Mybatis最重要的构建之一,可以简单的任务Mybatis一系列的配置目的是生成类似JDBC生成的Connection对象的SqlSession,这样才能和数据库开启“沟通的桥梁”,通过SqlSession可以实现增删改查(当然现在更加推荐是使用Mapper接口的形式),那么它是如何执行实现的呢?
(1)sqlsession简单原理介绍
sqlSession提供select、insert、update、delete方法,在旧版本中使用sqlsession接口的这些方法,但是在新版本中Mybatis就会建议直接使用mapper接口的方法。

映射器其实就是一个动态代理对象,进入到MapperMethod的execute方法就能简单找打sqlsession的删除,更新、查询、选择方法,从底层实现来说:通过动态代理技术,让接口跑起来,之后采用命令模式,最后还是采用了sqlsession的接口方法(getMapper()方法等到Mapper)执行sql查询(也就是说Mapper接口方法的底层实现还是采用了Sqlsession的接口方法实现的)。
(2)SqlSession的四个重要对象

1)Execute:调度执行StatementHandler、ParmmeterHandler、ResultHandler执行相应的SQL语句;

2)StatementHandler:使用数据库中的Statement(PrepareStatement)执行操作,即底层是封装好的PrepareStatement;

3)ParammeterHandler:处理SQL参数;

4)ResultHandler:结果集ResultSet封装处理放回。

public class MybatisTest {
    
    
    private static SqlSession sqlSession;

    @BeforeClass
    public static void init() {
    
    

        //
        //SqlSessionFactoryBuilder是构建sqlSessionFactory的入口类
        //第一步,创建一个sqlSessionFactoryBuilder构建类对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

        // 第二步
//        ClassLoader classLoader = MybatisTest.class.getClassLoader();
//        InputStream inputStream = classLoader.getResourceAsStream("mybatis-config.xml");
        InputStream inputStream = null;
        try {
    
    
            //Resources 类为从类路径中加载资源,提供了易于使用的方法。
            //
            //Resources 类试图简化这些工作,Resources 类常用于以下几种情况:
            //
            //1.从类路径加载 SQL Map 配置文件(如 sqlMap-config.xml)。
            //2. 从类路径加载 DAO Manager 配置文件(如 dao.xml)。
            //3. 从类路径加载各种.properties 文件。
            //
            //加载一个资源有很多方式,包括:
            //1.对于简单的只读文本数据,加载为 Reader。
            //Reader getResourceAsReader(String resource);
            //2. 对于简单的只读二进制或文本数据,加载为 Stream。
            //
            //Stream getResourceAsStream(String resource);
            //
            //3.对于可读写的二进制或文本文件,加载为 File。
            //
            //File getResourceAsFile(String resource);
            //
            //******此处用法4. 对于只读的配置属性文件,加载为 Properties。*********(看此处即可)
            //
            //Properties getResourceAsProperties(String resource);
            //
            //5. 对于只读的通用资源,加载为 URL。
            //按以上的顺序,Resources 类加载资源的方法如下:
            //
            //Url getResourceAsUrl(String resource);
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        //SqlSessionFactoryBuilder是利用XML或者Java编码获得资源来构建SqlSessionFactory。
        // 通过它可以构建过个SqlSessionFactory。它的作用就是一个构建器,
        // 一旦我们构建了SqlSessionFactory,它的作用也就消失了
       //此处的作用是通过一个sqlSessionFactoryBuilder对象,创建一个sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);

        // 第三步 获取sqlSession
        sqlSession = sqlSessionFactory.openSession();

    }


    @Test
    public void testSelectAll() {
    
    
        //第一步 创建sqlSessionFactoryBuilder(与数据库之间的会话的工厂)
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

        //第二步 读取配置文件
//    ClassLoader classLoader = MybatisTest.class.getClassLoader();
//    InputStream inputStream = classLoader.getResourceAsStream("mybatis-config.xml");

        //改进版第二步
        InputStream inputStream = null;
        try {
    
    
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//第三步 获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

//第四步 执行sql
//	b, 查询所有用户
        List<Object> list = sqlSession.selectList("dao.StudentMapper.selectAll");

//输出
        for (Object object : list) {
    
    
            System.out.println(object);
        }
        //关闭资源
        sqlSession.close();

    }

    

//a.根据名字查询用户
@Test
    public void testSelectOneByName(){
    
    
    Student student = sqlSession.selectOne("dao.StudentMapper.selectOneByName", "唐僧");
    System.out.println(student);
}


//	c, 根据id删除用户
@Test
public void testDeletById(){
    
    
        //返回影响行数
    int student = sqlSession.delete("deleteStudentById", 3);
    System.out.println(student);
    sqlSession.commit();
}

//	d, 修改用户名字

    @Test
    public void testUpdateByName(){
    
    
        int student = sqlSession.update("updateName", "如来");
        System.out.println(student);
    }


    @AfterClass
    public static void destory() {
    
    
        sqlSession.close();
    }
}

3.6.2 结果:

建立数据库语句:

CREATE TABLE `student` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` varchar(5) DEFAULT NULL,
  `address` varchar(100) DEFAULT NULL,
  `math` int(11) DEFAULT NULL,
  `english` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

(1)查询所有用户
在这里插入图片描述
(2)根据名字查询用户
在这里插入图片描述
(3)修改用户名字
在这里插入图片描述

(4)根据id删除用户
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/gy99csdn/article/details/114679404
今日推荐