image.png
    image.png
    image.png
    image.png

    1. package com.itheima.pojo;
    2. import org.apache.ibatis.io.Resources;
    3. import org.apache.ibatis.session.SqlSession;
    4. import org.apache.ibatis.session.SqlSessionFactory;
    5. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    6. import java.io.IOException;
    7. import java.io.InputStream;
    8. import java.util.List;
    9. public class MyBatisDemo {
    10. public static void main(String[] args) throws Exception {
    11. // 1. 加载mybatis的核心配置文件,获取SqlSessionFactory (sql会话工厂)
    12. String resource = "mybatis-config.xml";
    13. InputStream inputStream = Resources.getResourceAsStream(resource);
    14. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    15. // 2. 获取SqlSession对象,用它来执行sql
    16. SqlSession sqlSession = sqlSessionFactory.openSession();
    17. // 3. 执行sql
    18. // 由于里面的sql语句是查询所有字段 :select * from tb_user;, 所以要用selectList的API,查询一个就用selectone
    19. List<User> users = sqlSession.selectList("test.selectAll");// 参数是 空间名.标识名(id)
    20. // 打印查到的字段数据集合
    21. System.out.println(users);
    22. // 4.释放资源
    23. sqlSession.close();
    24. }
    25. }
    1. package com.itheima.pojo;
    2. public class User {
    3. private Integer id;
    4. private String username;
    5. private String password;
    6. private String gender;
    7. private String addr;
    8. public Integer getId() {
    9. return id;
    10. }
    11. public void setId(Integer id) {
    12. this.id = id;
    13. }
    14. public String getUsername() {
    15. return username;
    16. }
    17. public void setUsername(String username) {
    18. this.username = username;
    19. }
    20. public String getPassword() {
    21. return password;
    22. }
    23. public void setPassword(String password) {
    24. this.password = password;
    25. }
    26. public String getGender() {
    27. return gender;
    28. }
    29. public void setGender(String gender) {
    30. this.gender = gender;
    31. }
    32. public String getAddr() {
    33. return addr;
    34. }
    35. public void setAddr(String addr) {
    36. this.addr = addr;
    37. }
    38. @Override
    39. public String toString() {
    40. return "User{" +
    41. "id=" + id +
    42. ", username='" + username + '\'' +
    43. ", password='" + password + '\'' +
    44. ", gender='" + gender + '\'' +
    45. ", addr='" + addr + '\'' +
    46. '}';
    47. }
    48. }