环境准备:
Jdk环境:jdk1.7.0_72
Ide环境:eclipse indigo
数据库环境:MySQL 5.1
Mybatis:3.2.7
下载mybatis
mybaits的代码由github.com管理,下载地址:https://github.com/mybatis/mybatis-3/releases
Lib:mybatis的依赖包
Mybatis-3.2.7.jar:mybatis的核心包
Mybatis-3.2.7.pdf:mybatis的使用指南
任务需求
对用户信息的增删改查操作。
1、 根据用户ID来查询用户信息;
2、 根据用户名称来模糊查询用户信息列表;
3、 添加用户
4、 删除用户(练习)
5、 修改用户(练习)
数据库设计
create database mybatis
use mybatis
CREATE TABLE `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL COMMENT '商品名称',
`price` float(10,1) NOT NULL COMMENT '商品定价',
`detail` text COMMENT '商品描述',
`pic` varchar(64) DEFAULT NULL COMMENT '商品图片',
`createtime` datetime NOT NULL COMMENT '生产日期',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/*Table structure for table `orderdetail` */
CREATE TABLE `orderdetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`orders_id` int(11) NOT NULL COMMENT '订单id',
`items_id` int(11) NOT NULL COMMENT '商品id',
`items_num` int(11) DEFAULT NULL COMMENT '商品购买数量',
PRIMARY KEY (`id`),
KEY `FK_orderdetail_1` (`orders_id`),
KEY `FK_orderdetail_2` (`items_id`),
CONSTRAINT `FK_orderdetail_1` FOREIGN KEY (`orders_id`) REFERENCES `orders` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_orderdetail_2` FOREIGN KEY (`items_id`) REFERENCES `items` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*Table structure for table `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;
/*Table structure for table `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;
工程搭建
Mybatis的核心包和依赖包
MySQl的驱动包
Junit(非必须)
编程步骤
1、创建PO类,根据需求创建;
2、创建全局配置文件SqlMapConfig.xml;
3、编写映射文件;
4、加载映射文件,在SqlMapConfig.xml中进行加载;
5、编写测试程序,即编写Java代码,连接并操作数据库。
思路:
a)读取配置文件;
b)通过SqlSessionFactoryBuilder创建SqlSessionFactory会话工厂。
c)通过SqlSessionFactory创建SqlSession。
d)调用SqlSession的操作数据库方法。
e)关闭SqlSession。
2、创建全局配置文件SqlMapConfig.xml;
3、编写映射文件;
4、加载映射文件,在SqlMapConfig.xml中进行加载;
5、编写测试程序,即编写Java代码,连接并操作数据库。
思路:
a)读取配置文件;
b)通过SqlSessionFactoryBuilder创建SqlSessionFactory会话工厂。
c)通过SqlSessionFactory创建SqlSession。
d)调用SqlSession的操作数据库方法。
e)关闭SqlSession。