package com.lc.mybatis.test;

import com.lc.mybatis.entity.User;
import com.lc.mybatis.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMybatis {




    @Test
    public void test01() throws IOException {
        //构建sqlSessionfactory
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory  = new SqlSessionFactoryBuilder().build(is);
        //获取 SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //获取接口  jdk动态代理 UserMapper 代理类 反射技术
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用
        User user = new User();
        user.setUsername("zs01");
        user.setPassword("123456");
        user.setGender("m");
        user.setAddress("北京");

        mapper.addUser(user);

        Integer id = user.getId();
        System.out.println("主键："+id);

        //释放
        sqlSession.close();
    }

    @Test
    public void test02() throws IOException {
        //构建sqlSessionfactory
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //获取 SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //获取接口  jdk动态代理 UserMapper 代理类 反射技术
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用
        List<User> userList = mapper.getUserList("id","desc");

        userList.forEach(System.out::println);

    }

}
