- 新建数据库和表
CREATE DATAbase `mybatis`; USE `mybatis`; CREATE TABLE `user`( `id` INT(20) NOT NULL PRIMARY key, `name` VARCHAR(30) DEFAULT NULL, `pwd` VARCHAR(30) DEFAULT NULL )ENGINE=INNODB DEFAULT CHARSET=utf8; INSERT INTO `user` (id,name,pwd) VALUES (1,'mm1','mm1pwd'), (2,'mm2','mm1pwd'), (3,'mm3','mm1pwd');
- 新建一个maven项目
- 删除src
- 导入依赖
mysql mysql-connector-java 8.0.23 org.mybatis mybatis 3.4.6 junit junit 4.12 test
5.mybatis核心配置文件
- 编写mybatis工具类
// sqlSessionFactory
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory = null;
static{
try {
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
7.编写pojo类
public class User implements Serializable {
private Integer id;
private String name;
private String pwd;
}
8编写dao接口
public interface UserDao {
List getUserList();
}
9.编写UserDao.xml
select * from mybatis.user
10.在核心配置文件中注册mapper
11.编写测试类
@Test
public void test(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
List userList = userDao.getUserList();
System.out.println(userList.toString());
sqlSession.close();
}



