MyBatis(一)

package com.hitenine.dao;

import com.hitenine.pojo.User;
import com.hitenine.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {

@Test
public void test() {

    //第一步:获得SqlSession对象
    SqlSession sqlSession;
    sqlSession = MybatisUtils.getSqlSession();
    //执行SQL 方式一:getMapper  官方推荐!!
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    List<User> userList = mapper.getUserList();

    //方式二: 不推荐

// List userList = sqlSession.selectList("com.hitenine.dao.UserDao.getUserList");

for (User user : userList) {
        System.out.println(user);
    }

    //关闭SqlSessoin
    sqlSession.close();
}

/*
官方建议这样做
//第一步:获得SqlSession对象
    SqlSession sqlSession = MybatisUtils.getSqlSession();;
    try {
        //执行SQL 方式一:getMapper  官方推荐!!
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userList = mapper.getUserList();

        //方式二: 不推荐

// List userList = sqlSession.selectList("com.hitenine.dao.UserDao.getUserList");

for (User user : userList) {
            System.out.println(user);
        }

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        //关闭SqlSessoin
        sqlSession.close();
    }
 */

}