mybatis入门案例
在之前的mapper文件中加入
resultType="com.itheima.domain.User"
以告诉mybatis我要的返回值类型
接着编写测试类,MybatisTest.java:
package com.itheima; import com.itheima.dao.IUserDao; import com.itheima.domain.User; 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 java.io.InputStream; import java.util.List; public class MybatisTes { /** * 案例 * @param args */ public static void main(String[] args) throws Exception{ //1.读取配置文件 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.创建SqlSessionFactory工厂 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(in); //3.使用创建SqlSessionFactory工厂生产SqlSession对象 SqlSession session = factory.openSession(); //4.使用SqlSession对象创建Dao接口的代理对象 IUserDao userDao = session.getMapper(IUserDao.class); //5.使用代理对象执行方法 List<User> users = userDao.findall(); for (User user : users){ System.out.println(user); } //6.释放资源 session.close(); in.close(); } }
运行结果: