目录
导入mybatis的parent项目
导入mybatis的项目
新建一个maven项目
增加配置文件
增加resources目录
在resources文件夹添加mybatis-config.xml
在resources文件夹添加log4j.properties
pom文件修改
增加应用文件
包com.test.model里新建实体类,以SysUser为例
包com.test.mapper里新建接口,以UserMapper为例
resources文件夹中逐个新建包com.test.mapper, 然后新建xml文件UserMapper.xml
在项目com.test包,新建测试父类BaseMapperTest类
在项目com.test包,新建名为UserMapperTest的java类
resources下建立mybatis_test.sql,并执行
执行文件
现有的源码
git导入 https://github.com/mybatis/parent
生成一个项目 master分支
https://github.com/mybatis/mybatis-3
或者
https://github.com/tuguangquan/mybatis
目前导入的是下面那个,中文注释版,master分支
注意:修改密码,注意数据库名称
#全局配置
log4j.rootLogger=ERROR, stdout
#MyBatis日志配置
log4j.logger.com.test.mapper=TRACE
#控制台输出配置
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
增加
mysql
mysql-connector-java
5.1.47
package com.test.model;
import java.sql.Timestamp;
/**
* sys_user实体类
*
* @author
*
*/
public class SysUser {
/**用户ID*/
private Long id;
/**用户名*/
private String userName;
/**密码*/
private String userPassword;
/**邮箱*/
private String userEmail;
/**简介*/
private String userInfo;
/**头像*/
private String headImg;
/**创建时间*/
private Timestamp createTime;
/**
* 实例化
*/
public SysUser() {
super();
}
/**
* 获取id
*
* @return
*/
public Long getId() {
return id;
}
/**
* 设置id
*
* @param id
*/
public void setId(Long id) {
this.id = id;
}
/**
* 获取userName
*
* @return
*/
public String getUserName() {
return userName;
}
/**
* 设置userName
*
* @param userName
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* 获取userPassword
*
* @return
*/
public String getUserPassword() {
return userPassword;
}
/**
* 设置userPassword
*
* @param userPassword
*/
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
/**
* 获取userEmail
*
* @return
*/
public String getUserEmail() {
return userEmail;
}
/**
* 设置userEmail
*
* @param userEmail
*/
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
/**
* 获取userInfo
*
* @return
*/
public String getUserInfo() {
return userInfo;
}
/**
* 设置userInfo
*
* @param userInfo
*/
public void setUserInfo(String userInfo) {
this.userInfo = userInfo;
}
/**
* 获取headImg
*
* @return
*/
public String getHeadImg() {
return headImg;
}
/**
* 设置headImg
*
* @param headImg
*/
public void setHeadImg(String headImg) {
this.headImg = headImg;
}
public Timestamp getCreateTime() {
return createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "SysUser [id=" + id + " , userName=" + userName + " , userPassword=" + userPassword + " , userEmail=" + userEmail + " , userInfo=" + userInfo + " , headImg=" + headImg + " , createTime=" + createTime + " ]";
}
}
package com.test.mapper;
import java.util.List;
import com.test.model.SysUser;
public interface UserMapper {
SysUser selectByid(Long id);
List selectAll();
}
package com.test;
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 org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.rules.TestName;
import java.io.IOException;
import java.io.Reader;
public class BaseMapperTest {
private static SqlSessionFactory sqlSessionFactory;
@Rule
public TestName name= new TestName();
@BeforeClass
public static void init() {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
reader.close();
} catch (IOException ignore) {
ignore.printStackTrace();
}
}
public SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
@Before
public void runBeforeTestMethod() {
System.out.println("@Before "+ name.getMethodName());
}
@After
public void runAfterTestMethod() {
System.out.println("@After "+ name.getMethodName());
System.out.println();
}
}
package com.test;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import com.test.model.SysUser;
import java.util.List;
public class UserMapperTest extends BaseMapperTest {
@Test
public void testUserSelectAll() {
SqlSession sqlSession = getSqlSession();
try {
List sysUsers=sqlSession.selectList("com.test.mapper.UserMapper.selectAll");
for (SysUser user: sysUsers){
System.out.println(user.getUserName());
}
} finally {
sqlSession.close();
}
}
@Test
public void testUserSelectById() {
SqlSession sqlSession = getSqlSession();
try {
SysUser sysUser = sqlSession.selectOne("com.test.mapper.UserMapper.selectByid", 1);
System.out.println(sysUser.getUserName());
} finally {
sqlSession.close();
}
}
}
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50723
Source Host : localhost:3306
Source Database : mybatis
Target Server Type : MYSQL
Target Server Version : 50723
File Encoding : 65001
Date: 2018-11-02 18:02:14
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for country
-- ----------------------------
DROP TABLE IF EXISTS `country`;
CREATE TABLE `country` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`countryname` varchar(255) DEFAULT NULL,
`countrycode` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of country
-- ----------------------------
INSERT INTO `country` VALUES ('1', '中国', 'CN');
INSERT INTO `country` VALUES ('2', '美国', 'US');
INSERT INTO `country` VALUES ('3', '俄罗斯', 'RU');
INSERT INTO `country` VALUES ('4', '英国', 'GB');
INSERT INTO `country` VALUES ('5', '法国', 'FR');
-- ----------------------------
-- Table structure for sys_dict
-- ----------------------------
DROP TABLE IF EXISTS `sys_dict`;
CREATE TABLE `sys_dict` (
`id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '主键',
`code` varchar(64) NOT NULL COMMENT '类别',
`name` varchar(64) NOT NULL COMMENT '字典名',
`value` varchar(64) NOT NULL COMMENT '字典值',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_dict
-- ----------------------------
INSERT INTO `sys_dict` VALUES ('1', '性别', '男', '男');
INSERT INTO `sys_dict` VALUES ('2', '性别', '女', '女');
INSERT INTO `sys_dict` VALUES ('3', '季度', '第一季度', '1');
INSERT INTO `sys_dict` VALUES ('4', '季度', '第二季度', '2');
INSERT INTO `sys_dict` VALUES ('5', '季度', '第三季度', '3');
INSERT INTO `sys_dict` VALUES ('6', '季度', '第四季度', '4');
-- ----------------------------
-- Table structure for sys_privilege
-- ----------------------------
DROP TABLE IF EXISTS `sys_privilege`;
CREATE TABLE `sys_privilege` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '权限ID',
`privilege_name` varchar(50) DEFAULT NULL COMMENT '权限名称',
`privilege_url` varchar(200) DEFAULT NULL COMMENT '权限URL',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='权限表';
-- ----------------------------
-- Records of sys_privilege
-- ----------------------------
INSERT INTO `sys_privilege` VALUES ('1', '用户管理', '/users');
INSERT INTO `sys_privilege` VALUES ('2', '角色管理', '/roles');
INSERT INTO `sys_privilege` VALUES ('3', '系统日志', '/logs');
INSERT INTO `sys_privilege` VALUES ('4', '人员维护', '/persons');
INSERT INTO `sys_privilege` VALUES ('5', '单位维护', '/companies');
-- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '角色ID',
`role_name` varchar(50) DEFAULT NULL COMMENT '角色名',
`enabled` int(11) DEFAULT NULL COMMENT '有效标志',
`create_by` bigint(20) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='角色表';
-- ----------------------------
-- Records of sys_role
-- ----------------------------
INSERT INTO `sys_role` VALUES ('1', '管理员', '1', '1', '2016-04-01 17:02:14');
INSERT INTO `sys_role` VALUES ('2', '普通用户', '1', '1', '2016-04-01 17:02:34');
-- ----------------------------
-- Table structure for sys_role_privilege
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_privilege`;
CREATE TABLE `sys_role_privilege` (
`role_id` bigint(20) DEFAULT NULL COMMENT '角色ID',
`privilege_id` bigint(20) DEFAULT NULL COMMENT '权限ID'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='角色权限关联表';
-- ----------------------------
-- Records of sys_role_privilege
-- ----------------------------
INSERT INTO `sys_role_privilege` VALUES ('1', '1');
INSERT INTO `sys_role_privilege` VALUES ('1', '3');
INSERT INTO `sys_role_privilege` VALUES ('1', '2');
INSERT INTO `sys_role_privilege` VALUES ('2', '4');
INSERT INTO `sys_role_privilege` VALUES ('2', '5');
-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`user_name` varchar(50) DEFAULT NULL COMMENT '用户名',
`user_password` varchar(50) DEFAULT NULL COMMENT '密码',
`user_email` varchar(50) DEFAULT '[email protected]' COMMENT '邮箱',
`user_info` text COMMENT '简介',
`head_img` blob COMMENT '头像',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1009 DEFAULT CHARSET=utf8 COMMENT='用户表';
-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES ('1', 'admin', '123456', '[email protected]', '管理员用户', 0x1231231230, '2019-06-07 01:11:12');
INSERT INTO `sys_user` VALUES ('2', 'xusy', '1234', '[email protected]', '用户', 0x1235423121, '2018-06-07 01:11:12');
-- ----------------------------
-- Table structure for sys_user_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`user_id` bigint(20) DEFAULT NULL COMMENT '用户ID',
`role_id` bigint(20) DEFAULT NULL COMMENT '角色ID'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户角色关联表';
-- ----------------------------
-- Records of sys_user_role
-- ----------------------------
INSERT INTO `sys_user_role` VALUES ('1', '1');
INSERT INTO `sys_user_role` VALUES ('1', '2');
INSERT INTO `sys_user_role` VALUES ('1001', '2');
-- ----------------------------
-- Table structure for userinfo
-- ----------------------------
DROP TABLE IF EXISTS `userinfo`;
CREATE TABLE `userinfo` (
`id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of userinfo
-- ----------------------------
得到结果
@Before testUserSelectById
admin
@After testUserSelectById
@Before testUserSelectAll
admin
xusy
@After testUserSelectAll
mybatis-parent源码可以拉
https://gitee.com/xushiyu/mybatis_parent_source_code
mybatis的源码可以拉
https://gitee.com/xushiyu/mybatis_source_code_annotation
注意:这个版本是 https://github.com/tuguangquan/mybatis 复制了这个项目的mybatis源码和中文注释,并增加了自己的测试代码和注释(就是加入了本文章的逻辑)
注意:拉下后,如果没有src/main/resources,可以自己新建一个,里面的文件会自动出现