使用idea加maven编写的mybatis入门程序

最近在看mybatis,跟着视频教程,但是上面用的是eclipse,但是不想在用eclipse了,打算用一下maven,由于之前没有用过,感觉网上的教程说的不是特别清楚,所以这里记录一下。
这里用的idea版本是2018.3.5,maven是3.6.1。

1 数据库的准备

首先需要需要创建一个数据库,这里我用了视频教程上的一个脚本:

/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50521
Source Host           : localhost:3306
Source Database       : mybatis

Target Server Type    : MYSQL
Target Server Version : 50521
File Encoding         : 65001

Date: 2015-04-09 16:03:53
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `orders`
-- ----------------------------
DROP TABLE IF EXISTS `orders`;
CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL COMMENT '下单用户id',
  `number` varchar(32) NOT NULL COMMENT '订单号',
  `createtime` datetime NOT NULL COMMENT '创建订单时间',
  `note` varchar(100) DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`id`),
  KEY `FK_orders_1` (`user_id`),
  CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of orders
-- ----------------------------
INSERT INTO `orders` VALUES ('3', '1', '1000010', '2015-02-04 13:22:35', null);
INSERT INTO `orders` VALUES ('4', '1', '1000011', '2015-02-03 13:22:41', null);
INSERT INTO `orders` VALUES ('5', '10', '1000012', '2015-02-12 16:13:23', null);

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `sex` char(1) DEFAULT NULL COMMENT '性别',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '王五', null, '2', null);
INSERT INTO `user` VALUES ('10', '张三', '2014-07-10', '1', '北京市');
INSERT INTO `user` VALUES ('16', '张小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('22', '陈小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('24', '张三丰', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('25', '陈小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('26', '王五', null, null, null);

可以先新建一个数据库,然后执行上面的脚本。

2 导入相关的jar包和依赖

2.1 新建项目

新建一个maven项目,直接默认就行,不用选择里面的模板。
使用idea加maven编写的mybatis入门程序_第1张图片
点击next,然后输入相应的坐标,就可以新建项目,比如我新建的项目:使用idea加maven编写的mybatis入门程序_第2张图片

2.2 导入依赖

在pom文件里导入的依赖主要有:mysql的驱动,mybatis,log4j(用于日志的打印),junit(用于单元测试),


        
        
            mysql
            mysql-connector-java
            5.1.35
        
        
            org.mybatis
            mybatis
            3.2.7
        
        
            junit
            junit
            RELEASE
            compile
        
        
            log4j
            log4j
            1.2.17
        
    

3 配置mybatis

3.1 创建实体类和对应的mapper文件

我新建了一个包com.itheima.pojo,创建的实体类是在这个包下。

public class User {
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String username;// 用户姓名
    private String sex;// 性别
    private Date birthday;// 生日
    private String address;// 地址
    //还有get和set方法
    }

对应的xml文件,是在resource目录下,我新建了一个mapper文件夹,因为maven中中默认是只会打包 resource下的资源文件。





    
    
    
    

    

3.2创建mybatis的核心配置文件

SqlMapConfig.xml里面的内容如下:




    
    
        
    
    
        
            
            
            
            
                
                
                
                
            
        
    
    
        
    

3.3 添加日志

在resoure目录下,新建log4j.properties文件

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

4 编写测试类

public class MybatisFirstTest {

    @Test
    public void testMybatis() throws Exception {
        //加载核心配置文件
        String resource = "SqlMapConfig.xml";
        InputStream in = Resources.getResourceAsStream(resource);
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //执行Sql语句
        User user = sqlSession.selectOne("User.queryUserById", 1); //这个是对应命名空间加上

        System.out.println(user);
    }
  }

运行结果如下:
使用idea加maven编写的mybatis入门程序_第3张图片

你可能感兴趣的:(mybatis)