对Mybatis的CRUD操作大全(传统dao开发)进行代码优化

关于上一篇的操作我们发现,存在大量的重复代码。为了提高开发的效率。我们将代码进行优化,我们将一些重复的代码提取出来。

Mybatis的CRUD操作大全(传统dao开发)

和Mybatis的传统dao1~7的步骤一样开发一样,可直接略
原先的代码长这个样子

package com.ithemo.test;

import com.ithemo.dao.StudentDao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.InputStream;

/**
 * 使用Junit单元测试:测试我们的配置
 */

public class MaybatisTest {
    @Test
    public void findStudentById() throws Exception {

        //1.读取配置文件,生产字节输入流
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4.获取代理对象
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        //5.执行查询
         mapper.deteleId(7);
        sqlSession.commit();
    }
}

进行代码优化之后

package com.ithemo.test;

import com.ithemo.dao.StudentDao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;

import java.io.InputStream;

/**
 * 使用Junit单元测试:测试我们的配置
 */

public class MaybatisTest {
    private InputStream in;
    private SqlSession sqlSession;
    private StudentDao studentDao;

    @Before//用于在测试方法执行之前执行
    public void init() throws Exception {
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        sqlSession = factory.openSession();
        //4.获取dao的代理对象
        studentDao = sqlSession.getMapper(StudentDao.class);
    }

    @After
    //用于在测试方法执行之后执行
    public void destroy() throws Exception {
        //提交事务
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        in.close();
    }
   //测试删除操作
    @Test
    public void testDelete() {
        studentDao.deteleId(6);
    }
    //测试保存操作
    @Test
    public void saveStudent(){
    Student student = new Student();
    studnet.setUid(8);
    student.setUname("梦想");
    student.setPassword(11223F);
    student.setBirthday(new Date());
    System.out.println(student); 
   }
}

一样可以运行,是不是代码简便了许多

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

眼里只有码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值