Mybatis-传统方式实现Dao

传统方式实现Dao层

Dao层传统实现方式

详细过程

数据准备

项目骨架

bean包

controller包(控制层)

service包(业务层)

Mapper包(持久层)

数据库相关配置jdbc.properties

核心配置文件MyBatisConfig.xml

映射配置文件StudentMapper.xml

LOG4J的配置和使用

步骤 


传统方式实现Dao层

Dao层传统实现方式

分层思想:控制层(controller)、业务层(service)、持久层(dao)

我们在之前的那一篇文章案例的基础上进行更改!

Mybatis-映射配置文件、核心配置文件_Tensorflow-CSDN博客https://blog.csdn.net/weixin_43715214/article/details/123139392上述文章也可以实现MyBatis数据库映射的功能,但是没有遵从三层架构的设计模式、

详细过程

数据准备

仍为db1数据库,student表

项目骨架

注意:里面的Dao没有用到,已经标明了!(懒得删除了hhh)

bean包

bean包里面的东西就是Student类,和原来的一样 

public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Student() {
    }

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

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

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

controller包(控制层)

controler是控制层,里面有StudentController,我们将其作为测试类,调用service层(业务层),所以在控制层中,需要创建业务层的对象。

/*
    控制层测试类
 */
public class StudentController {
    //创建业务层对象
    private StudentService service = new StudentServiceImpl();

    //查询全部功能测试
    @Test
    public void selectAll() {
        List<Student> students = service.selectAll();
        for (Student stu : students) {
            System.out.println(stu);
        }
    }

    //根据id查询功能测试
    @Test
    public void selectById() {
        Student stu = service.selectById(3);
        System.out.println(stu);
    }

    //新增功能测试
    @Test
    public void insert() {
        Student stu = new Student(4,"赵六",26);
        Integer result = service.insert(stu);
        System.out.println(result);
    }

    //修改功能测试
    @Test
    public void update() {
        Student stu = new Student(4,"赵六",16);
        Integer result = service.update(stu);
        System.out.println(result);
    }

    //删除功能测试
    @Test
    public void delete() {
        Integer result = service.delete(5);
        System.out.println(result);
    }
}

service包(业务层)

StudentService是接口,在impl包下是其实现类,由于业务层要调用持久层,所以在StudentServiceImpl类中创建了持久层对象

StudentService

public interface StudentService {
    // 查询全部
    public abstract List<Student> selectAll();

    // 根据id查询
    public abstract Student selectById(Integer id);

    // 新增数据
    public abstract Integer insert(Student stu);

    // 修改数据
    public abstract Integer update(Student stu);

    // 删除数据
    public abstract Integer delete(Integer id);
}

StudentServiceImpl

package com.itheima.service.impl;

import com.itheima.bean.Student;
import com.itheima.mapper.StudentMapper;
import com.itheima.mapper.impl.StudentMapperImpl;
import com.itheima.service.StudentService;

import java.util.List;

/*
    业务层实现类
 */
public class StudentServiceImpl implements StudentService {

    //创建持久层对象
    private StudentMapper mapper = new StudentMapperImpl();

    @Override
    public List<Student> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public Student selectById(Integer id) {
        return mapper.selectById(id);
    }

    @Override
    public Integer insert(Student stu) {
        return mapper.insert(stu);
    }

    @Override
    public Integer update(Student stu) {
        return mapper.update(stu);
    }

    @Override
    public Integer delete(Integer id) {
        return mapper.delete(id);
    }
}

Mapper包(持久层)

就是原先的Dao层,只不过因为使用Mybatis,数据是由映射的来的所以叫做Mapper

StudentMapper

public interface StudentMapper {
    // 查询全部
    public abstract List<Student> selectAll();

    // 根据id查询
    public abstract Student selectById(Integer id);

    // 新增数据
    public abstract Integer insert(Student stu);

    // 修改数据
    public abstract Integer update(Student stu);

    // 删除数据
    public abstract Integer delete(Integer id);
}

StudentMapperImpl

public class StudentMapperImpl implements StudentMapper {
    @Override
    public List<Student> selectAll() {
        InputStream is = null;
        SqlSession sqlSession = null;
        List<Student> list = null;

        try {
            // 1.加载核心配置文件
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            // 2.获取SqlSessionFactory工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            // 3.通过SqlSessionFactory工厂对象获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);
            // 4.执行映射配置文件中的SQL语句,并收取结果
            list = sqlSession.selectList("StudentMapper.selectAll");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6.释放资源
            if (sqlSession != null) {
                sqlSession.close();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 5.处理结果放到了controller层,这里将list返回就行了!
        return list;
    }

    @Override
    public Student selectById(Integer id) {
        InputStream is = null;
        SqlSession sqlSession = null;
        Student stu = null;

        try {
            // 1.加载核心配置文件
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            // 2.获取SqlSessionFactory工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            // 3.通过SqlSessionFactory工厂对象获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);
            // 4.执行映射配置文件中的SQL语句,并收取结果
            stu = sqlSession.selectOne("StudentMapper.selectById",id);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6.释放资源
            if (sqlSession != null) {
                sqlSession.close();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 5.处理结果放到了controller层,这里将list返回就行了!
        return stu;
    }

    @Override
    public Integer insert(Student stu) {
        InputStream is = null;
        SqlSession sqlSession = null;
        Integer result = null;

        try {
            // 1.加载核心配置文件
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            // 2.获取SqlSessionFactory工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            // 3.通过SqlSessionFactory工厂对象获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);
            // 4.执行映射配置文件中的SQL语句,并收取结果
            // 这里的stu对象是控制层、业务层传递进来的!
            result = sqlSession.insert("StudentMapper.insert",stu);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6.释放资源
            if (sqlSession != null) {
                sqlSession.close();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 5.处理结果放到了controller层,这里将list返回就行了!
        return result;
    }

    @Override
    public Integer update(Student stu) {
        InputStream is = null;
        SqlSession sqlSession = null;
        Integer result = null;

        try {
            // 1.加载核心配置文件
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            // 2.获取SqlSessionFactory工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            // 3.通过SqlSessionFactory工厂对象获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);
            // 4.执行映射配置文件中的SQL语句,并收取结果
            result = sqlSession.update("StudentMapper.update",stu);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6.释放资源
            if (sqlSession != null) {
                sqlSession.close();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 5.处理结果放到了controller层,这里将list返回就行了!
        return result;
    }

    @Override
    public Integer delete(Integer id) {
        InputStream is = null;
        SqlSession sqlSession = null;
        Integer result = null;

        try {
            // 1.加载核心配置文件
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            // 2.获取SqlSessionFactory工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            // 3.通过SqlSessionFactory工厂对象获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);
            // 4.执行映射配置文件中的SQL语句,并收取结果
            result = sqlSession.delete("StudentMapper.delete",id);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6.释放资源
            if (sqlSession != null) {
                sqlSession.close();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 5.处理结果放到了controller层,这里将list返回就行了!
        return result;
    }
}

数据库相关配置jdbc.properties

在MyBatisConfig.xml中引用,进行数据库驱动的加载

<!-- 引入数据库连接的配置文件,在MyBatisConfig.xml配置 -->
<properties resource="jdbc.properties"/> 

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost/db1
username=root
password=888888

核心配置文件MyBatisConfig.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 核心根标签-->
<configuration>

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

    <!-- 配置log4j -->
    <settings>
        <setting name="logImpl" value="log4j"/>
    </settings>
    
    <!-- 起别名-->
    <typeAliases>
        <typeAlias type="com.itheima.bean.Student" alias="student"></typeAlias>
    </typeAliases>

    <!--environments配置数据库环境,环境可以有多个。default属性指定使用的是哪个-->
    <environments default="mysql">
        <!--environment配置数据库环境  id属性唯一标识-->
        <environment id="mysql">
            <!-- transactionManager事务管理。  type属性,采用JDBC默认的事务-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- dataSource数据源信息   type属性 连接池-->
            <dataSource type="POOLED">
                <!-- property获取数据库连接的配置信息 -->
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>

    <!-- mappers引入映射配置文件 -->
    <mappers>
        <!-- mapper 引入指定的映射配置文件   resource属性指定映射配置文件的名称 -->
        <mapper resource="StudentMapper.xml"></mapper>
    </mappers>

</configuration>

映射配置文件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属性:名称空间
-->
<mapper namespace="StudentMapper">
    <!--
    select:查询功能的标签
    id属性:唯一标识
    resultType属性:指定结果映射对象类型
    parameterType属性:指定参数映射对象类型
    -->
    <select id="selectAll" resultType="student">
        SELECT * FROM student
    </select>
    
    <select id="selectById" resultType="student" parameterType="int">
        SELECT * FROM student WHERE id = #{id}
    </select>

    <!--
        返回的是一个int类型的行数!所以可以省略resultType
        但是,SQL语句的参数id、name、age是从学生对象中来所以,要有parameterType
    -->
    <insert id="insert" parameterType="student">
        INSERT INTO student VALUES (#{id},#{name},#{age})
    </insert>

    <update id="update" parameterType="student">
        UPDATE student SET name = #{name},age = #{age} WHERE id = #{id}
    </update>

    <!-- java.lang.Integer -> int-->
    <delete id="delete" parameterType="int">
        DELETE FROM student WHERE id = #{id}
    </delete>
</mapper>

LOG4J的配置和使用

在日常开发过程中,排查问题时难免需要输出 MyBatis 真正执行的 SQL 语句、参数、结果等信息,我们就可以借助 LOG4J 的功能来实现执行信息的输出。

步骤 

核心配置MyBatisConfig.xml中<configuration>标签下

<!-- 配置log4j -->
<settings>
    <setting name="logImpl" value="log4j"/>
</settings>

在src下面新建log4.properties文件 

# Global logging configuration
# ERROR WARN INFO DEBUG
# error warn info debug
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

我们执行一下delete()的单元测试,控制台就不是像之前那样只是输出一个表示执行成功的“1”了。

而是输出SQL语句的执行步骤信息,如下:

posted @   金鳞踏雨  阅读(23)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示