zoukankan      html  css  js  c++  java
  • mybatis原始DAO开发

    一、mybatis开发中所需对象

    1、SqlSessionFactory

      通过SqlSessionFactoryBuilder创建会话工厂SqlSessionFactory,创建SqlSession,使用单例模式管理sqlSessionFactory(工厂一旦创建,使用一个实例)

    2、SqlSession

      SqlSession是线程不安全的,SqlSession最佳应用场合在方法体内,定义成局部变量使用

    二、原始dao开发方法(程序员需要写dao接口和dao实现类)

    dao需要操作数据库,那么就需要SqlSession对象,其对象是由SqlSessionFactory创建所以需要向dao实现类中注入SqlSessionFactory对象

      1、定义接口

    public interface UserDao {
        public User findUserById(int id);
    }

      2、接口实现类

    public class UserDaoImpl implements UserDao {
        //SqlSessionFactory
        private SqlSessionFactory sessionFactory;
        
        //使用构造方法注入
        public UserDaoImpl(SqlSessionFactory sessionFactory) {
        this.sessionFactory=sessionFactory;
        }
        
        public User findUserById(int id) {
        SqlSession sqlSession=sessionFactory.openSession();
        User user=sqlSession.selectOne("findUserById",id);
        return user;
        }
    }

      3、配置映射文件

        <select id="findUserById" parameterType="int" resultType="com.xxx.mybatis.po.User">
            select * from t_user where id = #{id}
        </select>

      4、核心配置文件

    <mapper resource="User.xml"/> 

      

       5、测试

    public class UserDaoImplTest {
        SqlSessionFactory sqlSessionFactory;
    
        @BeforeEach
        public void setUp() throws Exception {
        // mybatis核心配置文件
        String resource = "SqlMapConfig.xml";
        // 核心配置文件流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 根据核心配置文件,创建SqlSessionFactory对象
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }
    
        /**
         * Test method for {@link com.xxx.mybatis.dao.UserDaoImpl#findUserById(int)}.
         */
        @Test
        public void testFindUserById() {
        UserDao dao = new UserDaoImpl(sqlSessionFactory);
        User user = dao.findUserById(2);
        System.out.println(user);
        }
    
    }
    View Code

        在Junit4下使用@Before和@After,在Junit5下使用@BeforeEach和@AfterEach

  • 相关阅读:
    数制
    转移指令检测题9
    转移指令笔记(1)
    汇编笔记
    汇编语言学习笔记
    C++中的虚函数
    windows程序设计(四)
    windows程序设计(三)
    windows程序设计(二)
    通过Url网络编程实现下载
  • 原文地址:https://www.cnblogs.com/WarBlog/p/14930878.html
Copyright © 2011-2022 走看看