注意:本《MyBatis框架的使用及源码分析》素有章节只单纯地描述mybatis源码,不涵盖mybatis-spring的源码。
1、我们先来看一个例子,简单的了解一下mybatis的mapper接口方式的使用。
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
public class TestApp {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
UserInfo userInfoById = mapper.getUserInfoById(1L);
System.out.println(userInfoById);
} catch (Exception e) {
e.printStackTrace();
}finally {
sqlSession.close();
}
}
}
2、数据库表 user
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info` (
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
`sex` int(1) NULL DEFAULT NULL COMMENT '性别',
`create_date` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '创建日期',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '用户信息表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user_info
-- ----------------------------
INSERT INTO `user_info` VALUES (1, '小王', 0, '2019-11-05 10:06:36');
INSERT INTO `user_info` VALUES (2, '小明', 0, '2019-11-05 10:06:36');
INSERT INTO `user_info` VALUES (4, '小红', 1, '2019-11-05 10:06:36');
INSERT INTO `user_info` VALUES (8, '小孙', 0, '2019-11-05 10:02:20');
INSERT INTO `user_info` VALUES (9, '三叶', 1, '2019-11-05 10:06:36');
INSERT INTO `user_info` VALUES (10, '梨花', 1, '2019-11-05 10:47:52');
3、UserInfo.java
public class UserInfo {
Long id;
/**
* 名字
*/
private String userName;
}
4、UserInfoMaper.java
public interface UserInfoMapper {
UserInfo getUserInfoById(Long id);
}
5、UserInfoMapper.xml
id, user_name, sex, create_date
6、mybatis-config.xml
上面几个类,在后面的章节中,都会用到,最好本地确定能启动起来。这样也方便调试。
后面会分别解析如何加载mybatis.xml配置文件,如何解析Mapper.xml和解析Mppaer如何被代理了。
本文转自:https://www.cnblogs.com/zsg88/p/7533894.html