3.编写一个User类
public class User { private int id; private String name; private String password; public User() { } public User(int id, String name, String password) { this.id = id; this.name = name; this.password = password; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + '}'; } }
在数据库中建立对应的表(CRUD自己手写)
4.编写一个mybatis工具类,获得SqlSession对象
在java下建一个utils包,建立一个MybatisUtils工具类
//工具类 sqlSessionFactory -->sqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //使用mybatis获取sqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //既然有了 SqlSessionFactory,顾名思义, // 我们可以从中获得 SqlSession 的实例。SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。 // 你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。 public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(); } }
5.test进行测试,查询所有User
public class UserDaoMapperTest { @Test public void test(){ //1.获得sqlSession对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); //方法1:getMapper UserDaoMapper userDaoMapper = sqlSession.getMapper(UserDaoMapper.class); List<User> userList= userDaoMapper.getUserList(); for (User user:userList){ System.out.println(user); } //关闭sqlSession sqlSession.close(); } }