MyBatis编写hello world代码的方法
这篇文章主要介绍"MyBatis编写hello world代码的方法",在日常操作中,相信很多人在MyBatis编写hello world代码的方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"MyBatis编写hello world代码的方法"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
目录
准备 SQL 脚本下载需要的依赖 jar 包准备日志配置文件 & jdbc 配置编写 hello world
准备 SQL 脚本
这里我使用的数据库是 MySQL 7 版本 。表设计了 student (学生表) , course (课程表),score(分数表)脚本如下:
SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS = 0;-- ------------------------------ Table structure for course-- ----------------------------DROP TABLE IF EXISTS `course`;CREATE TABLE `course` ( `course_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '', PRIMARY KEY (`course_id`) USING BTREE) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;-- ------------------------------ Records of course-- ----------------------------INSERT INTO `course` VALUES (1, '仁德');INSERT INTO `course` VALUES (2, '霸道');INSERT INTO `course` VALUES (3, '兵法');INSERT INTO `course` VALUES (4, '骑马');INSERT INTO `course` VALUES (5, '射箭');INSERT INTO `course` VALUES (6, '防御');INSERT INTO `course` VALUES (7, '青龙偃月刀');INSERT INTO `course` VALUES (8, '丈八蛇矛');INSERT INTO `course` VALUES (9, '长枪');INSERT INTO `course` VALUES (10, '制衡');INSERT INTO `course` VALUES (11, '医术');INSERT INTO `course` VALUES (12, '观星');INSERT INTO `course` VALUES (13, '天文');INSERT INTO `course` VALUES (14, '地理');INSERT INTO `course` VALUES (15, '兵器');INSERT INTO `course` VALUES (16, '双股剑');INSERT INTO `course` VALUES (17, '龙胆');INSERT INTO `course` VALUES (18, '铁骑');-- ------------------------------ Table structure for score-- ----------------------------DROP TABLE IF EXISTS `score`;CREATE TABLE `score` ( `score_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, `student_id` int(10) UNSIGNED NOT NULL, `course_id` int(10) UNSIGNED NOT NULL, `score` decimal(65, 0) UNSIGNED NOT NULL, PRIMARY KEY (`score_id`) USING BTREE) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;-- ------------------------------ Records of score-- ----------------------------INSERT INTO `score` VALUES (1, 1, 7, 99);INSERT INTO `score` VALUES (2, 2, 8, 95);INSERT INTO `score` VALUES (3, 3, 17, 99);INSERT INTO `score` VALUES (4, 4, 5, 90);INSERT INTO `score` VALUES (5, 5, 18, 96);INSERT INTO `score` VALUES (6, 5, 9, 90);INSERT INTO `score` VALUES (7, 4, 9, 96);INSERT INTO `score` VALUES (8, 6, 1, 99);INSERT INTO `score` VALUES (9, 6, 3, 60);INSERT INTO `score` VALUES (10, 6, 16, 80);INSERT INTO `score` VALUES (11, 7, 12, 96);INSERT INTO `score` VALUES (12, 7, 13, 93);INSERT INTO `score` VALUES (13, 7, 14, 98);INSERT INTO `score` VALUES (14, 8, 12, 96);INSERT INTO `score` VALUES (15, 9, 10, 91);INSERT INTO `score` VALUES (16, 10, 2, 99);INSERT INTO `score` VALUES (17, 10, 3, 95);INSERT INTO `score` VALUES (18, 11, 11, 100);INSERT INTO `score` VALUES (19, 12, 15, 93);-- ------------------------------ Table structure for student-- ----------------------------DROP TABLE IF EXISTS `student`;CREATE TABLE `student` ( `student_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, `sex` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, `age` tinyint(4) UNSIGNED NOT NULL, `create_time` datetime(0) NOT NULL ON UPDATE CURRENT_TIMESTAMP(0), `modify_time` datetime(0) NOT NULL ON UPDATE CURRENT_TIMESTAMP(0), PRIMARY KEY (`student_id`) USING BTREE) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;-- ------------------------------ Records of student-- ----------------------------INSERT INTO `student` VALUES (1, '关羽', '男', 55, '2019-10-31 10:23:50', '2019-10-31 10:23:52');INSERT INTO `student` VALUES (2, '张飞', '男', 52, '2019-10-31 10:25:50', '2019-10-31 10:25:50');INSERT INTO `student` VALUES (3, '赵云', '男', 50, '2019-10-31 10:24:37', '2019-10-31 10:24:39');INSERT INTO `student` VALUES (4, '黄忠', '男', 60, '2019-10-31 10:25:06', '2019-10-31 10:25:08');INSERT INTO `student` VALUES (5, '马超', '男', 40, '2019-10-31 10:25:23', '2019-10-31 10:25:27');INSERT INTO `student` VALUES (6, '刘备', '男', 55, '2019-10-31 10:25:43', '2019-10-31 10:25:46');INSERT INTO `student` VALUES (7, '诸葛亮', '男', 30, '2019-10-31 10:26:05', '2019-10-31 10:26:07');INSERT INTO `student` VALUES (8, '郭嘉', '男', 25, '2019-10-31 10:26:32', '2019-10-31 10:26:35');INSERT INTO `student` VALUES (9, '孙权', '男', 27, '2019-10-31 10:26:51', '2019-10-31 10:26:53');INSERT INTO `student` VALUES (10, '曹操', '男', 60, '2019-10-31 10:27:08', '2019-10-31 10:27:10');INSERT INTO `student` VALUES (11, '华佗', '男', 70, '2019-10-31 10:27:23', '2019-10-31 10:27:25');INSERT INTO `student` VALUES (12, '孙尚香', '女', 25, '2019-10-31 10:27:42', '2019-10-31 10:27:45');SET FOREIGN_KEY_CHECKS = 1;
下载需要的依赖 jar 包
这里我使用的项目构建工具是 maven , 以下代码只选取 dependencies 标签部分 :
org.mybatis mybatis 3.5.3 junit junit 4.12 test org.projectlombok lombok 1.18.10 provided mysql mysql-connector-java 6.0.6 log4j log4j 1.2.17 org.slf4j slf4j-api 1.7.28
准备日志配置文件 & jdbc 配置
LOG 使用 log4j (mybatis log 支持中包含对 log4j 的支持)
lo4j.properties
log4j.rootLogger=TRACE, stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss.SSS} [%t] -[%c] -[%p]%m%nlog4j.logger.org.apache.ibatis=TRACE
jdbc.properties 配置
jdbc.driver=com.mysql.cj.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatis-demo?characterEncoding=utf8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghaijdbc.user=xxxjdbc.password=xxx
注意使用 mysql-connector-java 6 以上版本的时候需要指定serverTimezone 参数,否则启动时会报错。
编写 hello world 代码
1. 编写和数据库表对应的实体类
Student class
package org.hepeng.demo.mybatis.entity;import lombok.Data;import java.util.Date;/** * @author he peng */@Datapublic class Student { private Integer studentId; private String name; private String sex; private Byte age; private Date createTime; private Date modifyTime;}
Course class
package org.hepeng.demo.mybatis.entity;import lombok.Data;/** * @author he peng */@Datapublic class Course { private Integer courseId; private String name;}
Score class
package org.hepeng.demo.mybatis.entity;import lombok.Data;/** * @author he peng */@Datapublic class Score { private Integer scoreId; private Integer studentId; private Integer courseId; private Double score;}
2. 编写 mybatis 配置文件
mybatis-config.xml
3. 编写 mapper 配置文件
在 resources 目录下新建 mapper 目录 ,mapper 目录下新建 StudentMapper.xml ( mapper/StudentMapper.xml )
4. 编写测试代码
package org.hepeng.demo.mybatis;import lombok.extern.slf4j.Slf4j;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Assert;import org.junit.Before;import java.io.InputStream;import java.util.List;/** * @author he peng */@Slf4jpublic class Test { SqlSessionFactory sqlSessionFactory; @Before public void sqlSessionFactory() throws Exception { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @org.junit.Test public void helloWorld() { // sqlId = mapper.xml 中的 namespace.id String sqlId = "Student.selectAll"; List
5. 测试结果
经过以上这几步骤我们就完成了 mybatis hello world 的代码编写,经过测试成功运行。通过观察输出的日志也可以分析出 mybatis 的一些行为,认真仔细观察日志也是学习的一种不错的方法。完整代码在码云 https://gitee.com/kernelHP/java-demo 目录中的 mybatis-demo 下 ,编译前先选择 maven profile , 如图 :
这样做是为了方便测试不同的 mybatis 版本。这个 demo 使用的是 jdk 1.8 , 如果你的机器上没有安装 jdk 1.8 可以从这里下载到 https://jdk.java.net/ .
到此,关于"MyBatis编写hello world代码的方法"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!