整合mybatis

整合Mybatis

步骤:

1.导入相关jar包

  • junit
  • mybatis
  • mysql数据库
  • spring相关的
  • aop织入
  • mybatis-spring

2.编写配置文件

3.测试

复习mybatis

  1. 编写实体类
    @Data
    public class User {
    private int id;
    private String pwd;
    private String name;
    }

  2. 编写核心配置文件






















  3. 编写接口
    public interface UserMapper {
    public List selectUser();
    }

  4. 编写Mapper.xml


  5. 测试
    public class MyTest {

    @Test
    public void test() throws IOException {
    String resources="mybatis-config.xml";
    InputStream in = Resources.getResourceAsStream(resources);
    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
    SqlSession sqlSession = sessionFactory.openSession(true);

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List userList = mapper.selectUser();
    for (User user : userList) {
    System.out.println(user);
    }
    }
    }
    mybatis-spring

    1. 编写数据源






    2. sqlSessionFactory






    3. sqlSessionTemplate




    4. 需要给接口加实现类
      public class UserMapperImpl implements UserMapper{

      //我们所有的操作,原来都使用sqlSession来执行,现在都使用SqlSessionTemplate
      private SqlSessionTemplate sqlSession;

      public void setSqlSession(SqlSessionTemplate sqlSession) {
      this.sqlSession = sqlSession;
      }

      public List selectUser() {
      UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      return mapper.selectUser();
      }
      }

    5. 将自己写的实现类,注入到Spring中



    6. 测试使用即可
      public class MyTest {

      @Test
      public void test() throws IOException {

      ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
      UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
      for (User user : userMapper.selectUser()) {
      System.out.println(user);
      }

posted @ 2021-08-05 10:00  青歌与  阅读(50)  评论(0)    收藏  举报