从.net开发转Java开发也快有一年了,但是有些东西觉得还是要记录下,常言说: "好记性不如烂笔头"还是很有道理的, 所以本系列完全为自我学习系列, 记录java数据持久化框架mybatis
1,新建一个名为simple的maven项目:
2,既然是maven肯定离不开pom.xml文件
4.0.0
tk.mybatis
simple
0.0.1-SNAPSHOT
UTF-8
1.8
1.8
org.mybatis
mybatis
3.4.6
junit
junit
4.12
test
log4j
log4j
1.2.17
mysql
mysql-connector-java
5.1.47
3,在resources文件夹添加mybatis-config.xml
4,在resources文件夹添加log4j.properties
#全局配置
log4j.rootLogger=ERROR, stdout
#MyBatis日志配置
log4j.logger.tk.mybatis.simple.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
5,包tk.mybatis.simple.mapper里新建接口,以UserMapper为例
package tk.mybatis.simple.mapper;
import tk.mybatis.simple.model.SysUser;
public interface UserMapper {
SysUser selectByid(Long id);
}
6,包tk.mybatis.simple.model里新建实体类,以SysUser为例
package tk.mybatis.simple.model;
/**
* 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 java.time.Instant 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;
}
/**
* 获取createTime
*
* @return
*/
public java.time.Instant getCreateTime() {
return createTime;
}
/**
* 设置createTime
*
* @param createTime
*/
public void setCreateTime(java.time.Instant createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "SysUser [id=" + id + " , userName=" + userName + " , userPassword=" + userPassword + " , userEmail=" + userEmail + " , userInfo=" + userInfo + " , headImg=" + headImg + " , createTime=" + createTime + " ]";
}
}
7,resources文件夹中逐个新建包tk.mybatis.simple.mapper, 然后新建xml文件UserMapper.xml
8, 在项目test文件夹中新建包simple,新建测试父类BaseMapperTest类
package simple;
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.BeforeClass;
import java.io.IOException;
import java.io.Reader;
public class BaseMapperTest {
private static SqlSessionFactory sqlSessionFactory;
@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();
}
}
9,在项目test文件夹的simple包中,新建名为UserMapperTest的java类
package simple;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import tk.mybatis.simple.model.SysUser;
import java.util.List;
public class UserMapperTest extends BaseMapperTest {
@Test
public void testUserSelectAll() {
SqlSession sqlSession = getSqlSession();
try {
List sysUsers=sqlSession.selectList("tk.mybatis.simple.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("tk.mybatis.simple.mapper.UserMapper.selectByid", 1);
System.out.println(sysUser.getUserName());
} finally {
sqlSession.close();
}
}
}
10,然后打开UserMapperTest类
11, 结果
demo中数据库脚本, 新建名为mybatis的数据库, 然后执行下列脚本
/*
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, '2016-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
-- ----------------------------