前话:简单搭建一个环境

参考文档:mybatis官方文档

1.添加依赖


    org.mybatis
    mybatis
    3.5.1


    mysql
    mysql-connector-java
    5.1.6

2.添加mybatis配置文件






    
        
        
            
            
            
            
        
    


    


3.添加jdbc配置

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.80.4:3306/MyTestDb?useUnicode=true&characterEncoding=UTF-8
username=root
password=xm123456

4.测试demo

  • Blog.java
@Data
public class Blog {
    private Long id;
    private String name;
}
  • BlogMapper.java
public interface BlogMapper {
    /**
     * 根据id查询
     * @param id
     * @return
     */
    Blog queryById(Long id);
}
  • BlogMapper.xml



    

  • MybatisTest.java
public class MybatisTest {

    @Test
    public void test() {
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        SqlSession session = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            session = sqlSessionFactory.openSession();
            BlogMapper mapper = session.getMapper(BlogMapper.class);
            Blog blog = mapper.queryById(1L);
            System.out.println(blog);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            session.close();
        }
    }

}

你可能感兴趣的:(前话:简单搭建一个环境)