码迷,mamicode.com
首页 > 其他好文 > 详细

mybatis学习(一)

时间:2017-11-15 10:43:45      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:家居   lap   incr   tco   配置信息   def   必须   sql_mod   image   

 

1、Mybatis下载:

https://github.com/mybatis/mybatis-3/releases

 技术分享

 

2、环境搭建:

新建Java web项目,目录结构如下:

技术分享

 

1)将mybatis-3.1.1jar【mybatis核心jar】、mysql-connector-java-5.1.7-bin.jar【mysql连接驱动】放在WEB-INF目录下的lib目录中,全部选中,然后全部选中,鼠标右键单击add to buildPath(My Eclipse8.5会自动添加,10.7版本的需要手动添加)

2)my eclipse 添加dtd文件:

window==> preferences==>输入xml===>点击 XML CatLog====》

技术分享

找到技术分享这2个文件,按如下方式添加,Config 的key:    -//mybatis.org//DTD Config 3.0//EN,Mapper 的key:  -//mybatis.org//DTD Mapper 3.0//EN

技术分享

添加好如下:

技术分享

3)利用dtd模版创建RoleDao.xml ,UserDao.xml和mybatis-config.xml(具体步骤省略)

4)创建数据库和表,代码如下:

技术分享
  1 /*
  2 SQLyog 企业版 - MySQL GUI v8.14 
  3 MySQL - 5.5.40 : Database - smbms
  4 *********************************************************************
  5 */
  6 
  7 
  8 /*!40101 SET NAMES utf8 */;
  9 
 10 /*!40101 SET SQL_MODE=‘‘*/;
 11 
 12 /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
 13 /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
 14 /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=‘NO_AUTO_VALUE_ON_ZERO‘ */;
 15 /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
 16 
 17 CREATE DATABASE /*!32312 IF NOT EXISTS*/`smbms` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;
 18 smbmssmbms_user
 19 USE `smbms`;
 20 
 21 /*Table structure for table `smbms_address` */
 22 
 23 DROP TABLE IF EXISTS `smbms_address`;
 24 
 25 CREATE TABLE `smbms_address` (
 26   `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 主键ID,
 27   `contact` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 联系人姓名,
 28   `addressDesc` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 收货地址明细,
 29   `postCode` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 邮编,
 30   `tel` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 联系人电话,
 31   `createdBy` BIGINT(20) DEFAULT NULL COMMENT 创建者,
 32   `creationDate` DATETIME DEFAULT NULL COMMENT 创建时间,
 33   `modifyBy` BIGINT(20) DEFAULT NULL COMMENT 修改者,
 34   `modifyDate` DATETIME DEFAULT NULL COMMENT 修改时间,
 35   `userId` BIGINT(20) DEFAULT NULL COMMENT 用户ID,
 36   PRIMARY KEY (`id`)
 37 ) ENGINE=INNODB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
 38 
 39 /*Data for the table `smbms_address` */
 40 
 41 INSERT  INTO `smbms_address`(`id`,`contact`,`addressDesc`,`postCode`,`tel`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`,`userId`) VALUES (1,王丽,北京市东城区东交民巷44号,100010,13678789999,1,2016-04-13 00:00:00,NULL,NULL,1),(2,张红丽,北京市海淀区丹棱街3号,100000,18567672312,1,2016-04-13 00:00:00,NULL,NULL,1),(3,任志强,北京市东城区美术馆后街23号,100021,13387906742,1,2016-04-13 00:00:00,NULL,NULL,1),(4,曹颖,北京市朝阳区朝阳门南大街14号,100053,13568902323,1,2016-04-13 00:00:00,NULL,NULL,2),(5,李慧,北京市西城区三里河路南三巷3号,100032,18032356666,1,2016-04-13 00:00:00,NULL,NULL,3),(6,王国强,北京市顺义区高丽营镇金马工业区18号,100061,13787882222,1,2016-04-13 00:00:00,NULL,NULL,3);
 42 
 43 /*Table structure for table `smbms_bill` */
 44 
 45 DROP TABLE IF EXISTS `smbms_bill`;
 46 
 47 CREATE TABLE `smbms_bill` (
 48   `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 主键ID,
 49   `billCode` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 账单编码,
 50   `productName` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 商品名称,
 51   `productDesc` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 商品描述,
 52   `productUnit` VARCHAR(10) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 商品单位,
 53   `productCount` DECIMAL(20,2) DEFAULT NULL COMMENT 商品数量,
 54   `totalPrice` DECIMAL(20,2) DEFAULT NULL COMMENT 商品总额,
 55   `isPayment` INT(10) DEFAULT NULL COMMENT 是否支付(1:未支付 2:已支付),
 56   `createdBy` BIGINT(20) DEFAULT NULL COMMENT 创建者(userId),
 57   `creationDate` DATETIME DEFAULT NULL COMMENT 创建时间,
 58   `modifyBy` BIGINT(20) DEFAULT NULL COMMENT 更新者(userId),
 59   `modifyDate` DATETIME DEFAULT NULL COMMENT 更新时间,
 60   `providerId` BIGINT(20) DEFAULT NULL COMMENT 供应商ID,
 61   PRIMARY KEY (`id`)
 62 ) ENGINE=INNODB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
 63 
 64 /*Data for the table `smbms_bill` */
 65 
 66 INSERT  INTO `smbms_bill`(`id`,`billCode`,`productName`,`productDesc`,`productUnit`,`productCount`,`totalPrice`,`isPayment`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`,`providerId`) VALUES (1,BILL2016_001,洗发水、护发素,日用品-洗发、护发,,500.00,25000.00,2,1,2014-12-14 13:02:03,NULL,NULL,13),(2,BILL2016_002,香皂、肥皂、药皂,日用品-皂类,,1000.00,10000.00,2,1,2016-03-23 04:20:40,NULL,NULL,13),(3,BILL2016_003,大豆油,食品-食用油,,300.00,5890.00,2,1,2014-12-14 13:02:03,NULL,NULL,6),(4,BILL2016_004,橄榄油,食品-进口食用油,,200.00,9800.00,2,1,2013-10-10 03:12:13,NULL,NULL,7),(5,BILL2016_005,洗洁精,日用品-厨房清洁,,500.00,7000.00,2,1,2014-12-14 13:02:03,NULL,NULL,9),(6,BILL2016_006,美国大杏仁,食品-坚果,,300.00,5000.00,2,1,2016-04-14 06:08:09,NULL,NULL,4),(7,BILL2016_007,沐浴液、精油,日用品-沐浴类,,500.00,23000.00,1,1,2016-07-22 10:10:22,NULL,NULL,14),(8,BILL2016_008,不锈钢盘碗,日用品-厨房用具,,600.00,6000.00,2,1,2016-04-14 05:12:13,NULL,NULL,14),(9,BILL2016_009,塑料杯,日用品-杯子,,350.00,1750.00,2,1,2016-02-04 11:40:20,NULL,NULL,14),(10,BILL2016_010,豆瓣酱,食品-调料,,200.00,2000.00,2,1,2013-10-29 05:07:03,NULL,NULL,8),(11,BILL2016_011,海之蓝,饮料-国酒,,50.00,10000.00,1,1,2016-04-14 16:16:00,NULL,NULL,1),(12,BILL2016_012,芝华士,饮料-洋酒,,20.00,6000.00,1,1,2016-09-09 17:00:00,NULL,NULL,1),(13,BILL2016_013,长城红葡萄酒,饮料-红酒,,60.00,800.00,2,1,2016-11-14 15:23:00,NULL,NULL,1),(14,BILL2016_014,泰国香米,食品-大米,,400.00,5000.00,2,1,2016-10-09 15:20:00,NULL,NULL,3),(15,BILL2016_015,东北大米,食品-大米,,600.00,4000.00,2,1,2016-11-14 14:00:00,NULL,NULL,3),(16,BILL2016_016,可口可乐,饮料,,2000.00,6000.00,2,1,2012-03-27 13:03:01,NULL,NULL,2),(17,BILL2016_017,脉动,饮料,,1500.00,4500.00,2,1,2016-05-10 12:00:00,NULL,NULL,2),(18,BILL2016_018,哇哈哈,饮料,,2000.00,4000.00,2,1,2015-11-24 15:12:03,NULL,NULL,2);
 67 
 68 /*Table structure for table `smbms_provider` */
 69 
 70 DROP TABLE IF EXISTS `smbms_provider`;
 71 
 72 CREATE TABLE `smbms_provider` (
 73   `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 主键ID,
 74   `proCode` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 供应商编码,
 75   `proName` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 供应商名称,
 76   `proDesc` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 供应商详细描述,
 77   `proContact` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 供应商联系人,
 78   `proPhone` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 联系电话,
 79   `proAddress` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 地址,
 80   `proFax` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 传真,
 81   `createdBy` BIGINT(20) DEFAULT NULL COMMENT 创建者(userId),
 82   `creationDate` DATETIME DEFAULT NULL COMMENT 创建时间,
 83   `modifyDate` DATETIME DEFAULT NULL COMMENT 更新时间,
 84   `modifyBy` BIGINT(20) DEFAULT NULL COMMENT 更新者(userId),
 85   PRIMARY KEY (`id`)
 86 ) ENGINE=INNODB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
 87 
 88 /*Data for the table `smbms_provider` */
 89 
 90 INSERT  INTO `smbms_provider`(`id`,`proCode`,`proName`,`proDesc`,`proContact`,`proPhone`,`proAddress`,`proFax`,`createdBy`,`creationDate`,`modifyDate`,`modifyBy`) VALUES (1,BJ_GYS001,北京三木堂商贸有限公司,长期合作伙伴,主营产品:茅台、五粮液、郎酒、酒鬼酒、泸州老窖、赖茅酒、法国红酒等,张国强,13566667777,北京市丰台区育芳园北路,010-58858787,1,2013-03-21 16:52:07,NULL,NULL),(2,HB_GYS001,石家庄帅益食品贸易有限公司,长期合作伙伴,主营产品:饮料、水饮料、植物蛋白饮料、休闲食品、果汁饮料、功能饮料等,王军,13309094212,河北省石家庄新华区,0311-67738876,1,2016-04-13 04:20:40,NULL,NULL),(3,GZ_GYS001,深圳市泰香米业有限公司,初次合作伙伴,主营产品:良记金轮米,龙轮香米等,郑程瀚,13402013312,广东省深圳市福田区深南大道6006华丰大厦,0755-67776212,1,2014-03-21 16:56:07,NULL,NULL),(4,GZ_GYS002,深圳市喜来客商贸有限公司,长期合作伙伴,主营产品:坚果炒货.果脯蜜饯.天然花茶.营养豆豆.特色美食.进口食品.海味零食.肉脯肉,林妮,18599897645,广东省深圳市福龙工业区B2栋3楼西,0755-67772341,1,2013-03-22 16:52:07,NULL,NULL),(5,JS_GYS001,兴化佳美调味品厂,长期合作伙伴,主营产品:天然香辛料、鸡精、复合调味料,徐国洋,13754444221,江苏省兴化市林湖工业区,0523-21299098,1,2015-11-22 16:52:07,NULL,NULL),(6,BJ_GYS002,北京纳福尔食用油有限公司,长期合作伙伴,主营产品:山茶油、大豆油、花生油、橄榄油等,马莺,13422235678,北京市朝阳区珠江帝景1号楼,010-588634233,1,2012-03-21 17:52:07,NULL,NULL),(7,BJ_GYS003,北京国粮食用油有限公司,初次合作伙伴,主营产品:花生油、大豆油、小磨油等,王驰,13344441135,北京大兴青云店开发区,010-588134111,1,2016-04-13 00:00:00,NULL,NULL),(8,ZJ_GYS001,慈溪市广和绿色食品厂,长期合作伙伴,主营产品:豆瓣酱、黄豆酱、甜面酱,辣椒,大蒜等农产品,薛圣丹,18099953223,浙江省宁波市慈溪周巷小安村,0574-34449090,1,2013-11-21 06:02:07,NULL,NULL),(9,GX_GYS001,优百商贸有限公司,长期合作伙伴,主营产品:日化产品,李立国,13323566543,广西南宁市秀厢大道42-1号,0771-98861134,1,2013-03-21 19:52:07,NULL,NULL),(10,JS_GYS002,南京火头军信息技术有限公司,长期合作伙伴,主营产品:不锈钢厨具等,陈女士,13098992113,江苏省南京市浦口区浦口大道1号新城总部大厦A座903室,025-86223345,1,2013-03-25 16:52:07,NULL,NULL),(11,GZ_GYS003,广州市白云区美星五金制品厂,长期合作伙伴,主营产品:海绵床垫、坐垫、靠垫、海绵枕头、头枕等,梁天,13562276775,广州市白云区钟落潭镇福龙路20号,020-85542231,1,2016-12-21 06:12:17,NULL,NULL),(12,BJ_GYS004,北京隆盛日化科技,长期合作伙伴,主营产品:日化环保清洗剂,家居洗涤专卖、洗涤用品网、墙体除霉剂、墙面霉菌清除剂等,孙欣,13689865678,北京市大兴区旧宫,010-35576786,1,2014-11-21 12:51:11,NULL,NULL),(13,SD_GYS001,山东豪克华光联合发展有限公司,长期合作伙伴,主营产品:洗衣皂、洗衣粉、洗衣液、洗洁精、消杀类、香皂等,吴洪转,13245468787,山东济阳济北工业区仁和街21号,0531-53362445,1,2015-01-28 10:52:07,NULL,NULL),(14,JS_GYS003,无锡喜源坤商行,长期合作伙伴,主营产品:日化品批销,周一清,18567674532,江苏无锡盛岸西路,0510-32274422,1,2016-04-23 11:11:11,NULL,NULL),(15,ZJ_GYS002,乐摆日用品厂,长期合作伙伴,主营产品:各种中、高档塑料杯,塑料乐扣水杯(密封杯)、保鲜杯(保鲜盒)、广告杯、礼品杯,王世杰,13212331567,浙江省金华市义乌市义东路,0579-34452321,1,2016-08-22 10:01:30,NULL,NULL);
 91 
 92 /*Table structure for table `smbms_role` */
 93 
 94 DROP TABLE IF EXISTS `smbms_role`;
 95 
 96 CREATE TABLE `smbms_role` (
 97   `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 主键ID,
 98   `roleCode` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 角色编码,
 99   `roleName` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 角色名称,
100   `createdBy` BIGINT(20) DEFAULT NULL COMMENT 创建者,
101   `creationDate` DATETIME DEFAULT NULL COMMENT 创建时间,
102   `modifyBy` BIGINT(20) DEFAULT NULL COMMENT 修改者,
103   `modifyDate` DATETIME DEFAULT NULL COMMENT 修改时间,
104   PRIMARY KEY (`id`)
105 ) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
106 
107 /*Data for the table `smbms_role` */
108 
109 INSERT  INTO `smbms_role`(`id`,`roleCode`,`roleName`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`) VALUES (1,SMBMS_ADMIN,系统管理员,1,2016-04-13 00:00:00,NULL,NULL),(2,SMBMS_MANAGER,经理,1,2016-04-13 00:00:00,NULL,NULL),(3,SMBMS_EMPLOYEE,普通员工,1,2016-04-13 00:00:00,NULL,NULL);
110 
111 /*Table structure for table `smbms_user` */
112 
113 DROP TABLE IF EXISTS `smbms_user`;
114 
115 CREATE TABLE `smbms_user` (
116   `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 主键ID,
117   `userCode` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 用户编码,
118   `userName` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 用户名称,
119   `userPassword` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 用户密码,
120   `gender` INT(10) DEFAULT NULL COMMENT 性别(1:女、 2:男),
121   `birthday` DATE DEFAULT NULL COMMENT 出生日期,
122   `phone` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 手机,
123   `address` VARCHAR(30) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 地址,
124   `userRole` BIGINT(20) DEFAULT NULL COMMENT 用户角色(取自角色表-角色id),
125   `createdBy` BIGINT(20) DEFAULT NULL COMMENT 创建者(userId),
126   `creationDate` DATETIME DEFAULT NULL COMMENT 创建时间,
127   `modifyBy` BIGINT(20) DEFAULT NULL COMMENT 更新者(userId),
128   `modifyDate` DATETIME DEFAULT NULL COMMENT 更新时间,
129   PRIMARY KEY (`id`)
130 ) ENGINE=INNODB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
131 
132 /*Data for the table `smbms_user` */
133 
134 INSERT  INTO `smbms_user`(`id`,`userCode`,`userName`,`userPassword`,`gender`,`birthday`,`phone`,`address`,`userRole`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`) VALUES (1,admin,系统管理员,1234567,1,1983-10-10,13688889999,北京市海淀区成府路207号,1,1,2013-03-21 16:52:07,NULL,NULL),(2,liming,李明,0000000,2,1983-12-10,13688884457,北京市东城区前门东大街9号,2,1,2014-12-31 19:52:09,NULL,NULL),(5,hanlubiao,韩路彪,0000000,2,1984-06-05,18567542321,北京市朝阳区北辰中心12号,2,1,2014-12-31 19:52:09,NULL,NULL),(6,zhanghua,张华,0000000,1,1983-06-15,13544561111,北京市海淀区学院路61号,3,1,2013-02-11 10:51:17,NULL,NULL),(7,wangyang,王洋,0000000,2,1982-12-31,13444561124,北京市海淀区西二旗辉煌国际16层,3,1,2014-06-11 19:09:07,NULL,NULL),(8,zhaoyan,赵燕,0000000,1,1986-03-07,18098764545,北京市海淀区回龙观小区10号楼,3,1,2016-04-21 13:54:07,NULL,NULL),(10,sunlei,孙磊,0000000,2,1981-01-04,13387676765,北京市朝阳区管庄新月小区12楼,3,1,2015-05-06 10:52:07,NULL,NULL),(11,sunxing,孙兴,0000000,2,1978-03-12,13367890900,北京市朝阳区建国门南大街10号,3,1,2016-11-09 16:51:17,NULL,NULL),(12,zhangchen,张晨,0000000,1,1986-03-28,18098765434,朝阳区管庄路口北柏林爱乐三期13号楼,3,1,2016-08-09 05:52:37,1,2016-04-14 14:15:36),(13,dengchao,邓超,0000000,2,1981-11-04,13689674534,北京市海淀区北航家属院10号楼,3,1,2016-07-11 08:02:47,NULL,NULL),(14,yangguo,杨过,0000000,2,1980-01-01,13388886623,北京市朝阳区北苑家园茉莉园20号楼,3,1,2015-02-01 03:52:07,NULL,NULL),(15,zhaomin,赵敏,0000000,1,1987-12-04,18099897657,北京市昌平区天通苑3区12号楼,2,1,2015-09-12 12:02:12,NULL,NULL);
135 
136 /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
137 /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
138 /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
139 /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
140 
141 
142 select * from smbms_bill
143 select * from smbms_user
smbms_db.sql

5)根据数据库字userbiao he role 表的字段创建2个实体类:

技术分享
 1 package cn.smbms.xsh.entity;
 2 
 3 public class User {
 4 
 5     private Integer id;
 6     private String userCode;
 7     private String userName;
 8     private String userPassword;
 9     private Integer gender;
10 
11     public Integer getId() {
12         return id;
13     }
14 
15     public void setId(Integer id) {
16         this.id = id;
17     }
18 
19     public String getUserCode() {
20         return userCode;
21     }
22 
23     public void setUserCode(String userCode) {
24         this.userCode = userCode;
25     }
26 
27     public String getUserName() {
28         return userName;
29     }
30 
31     public void setUserName(String userName) {
32         this.userName = userName;
33     }
34 
35     public String getUsrePassword() {
36         return userPassword;
37     }
38 
39     public void setUsrePassword(String usrePassword) {
40         this.userPassword = usrePassword;
41     }
42 
43     public Integer getGender() {
44         return gender;
45     }
46 
47     public void setGender(Integer gender) {
48         this.gender = gender;
49     }
50 
51     @Override
52     public String toString() {
53         return "User [id=" + id + ", userCode=" + userCode + ", userName="
54                 + userName + ", usrePassword=" + userPassword + ", gender="
55                 + gender + "]";
56     }
57 
58 }
User实体类
技术分享
 1 package cn.smbms.xsh.entity;
 2 
 3 import java.util.Date;
 4 
 5 public class Role {
 6 
 7     private Integer id;//角色编号
 8     private String roleCode;//角色编码
 9     private String roleName;//角色名称
10     private Integer createdBy;//创建者
11     private Date creationDate;//创建时间
12     private Integer modifyBy;//修改者
13     private Date modifyDate;//修改时间
14 
15     public Integer getId() {
16         return id;
17     }
18 
19     public void setId(Integer id) {
20         this.id = id;
21     }
22 
23     public String getRoleCode() {
24         return roleCode;
25     }
26 
27     public void setRoleCode(String roleCode) {
28         this.roleCode = roleCode;
29     }
30 
31     public String getRoleName() {
32         return roleName;
33     }
34 
35     public void setRoleName(String roleName) {
36         this.roleName = roleName;
37     }
38 
39     public Integer getCreatedBy() {
40         return createdBy;
41     }
42 
43     public void setCreatedBy(Integer createdBy) {
44         this.createdBy = createdBy;
45     }
46 
47     public Date getCreationDate() {
48         return creationDate;
49     }
50 
51     public void setCreationDate(Date creationDate) {
52         this.creationDate = creationDate;
53     }
54 
55     public Integer getModifyBy() {
56         return modifyBy;
57     }
58 
59     public void setModifyBy(Integer modifyBy) {
60         this.modifyBy = modifyBy;
61     }
62 
63     public Date getModifyDate() {
64         return modifyDate;
65     }
66 
67     public void setModifyDate(Date modifyDate) {
68         this.modifyDate = modifyDate;
69     }
70 
71     @Override
72     public String toString() {
73         return "Role [id=" + id + ", roleCode=" + roleCode + ", roleName="
74                 + roleName + ", createdBy=" + createdBy + ", creationDate="
75                 + creationDate + ", modifyBy=" + modifyBy + ", modifyDate="
76                 + modifyDate + "]";
77     }
78 
79 }
Role实体类

6)创建数据访问层的dao接口,定义增删改查的方法:

insert,select ,update,delete标签中的id,必须是dao接口中定义的id,

技术分享
 1 package cn.smbms.xsh.dao;
 2 
 3 import java.util.List;
 4 
 5 import cn.smbms.xsh.entity.User;
 6 
 7 public interface UserDao {
 8     
 9     List<User> getAllUser();
10     
11     Integer addUser(User user);
12     
13     Integer update(User user);
14     
15     Integer delete(Integer id);
16 
17 }
UserDao 定义
技术分享
 1 package cn.smbms.xsh.dao;
 2 
 3 import java.util.List;
 4 
 5 import cn.smbms.xsh.entity.Role;
 6 
 7 public interface RoleDao {
 8     /**
 9      * 获取所有role
10      * 
11      * @return
12      */
13     List<Role> getAll();
14 
15     /**
16      * 删除
17      * 
18      * @param id
19      * @return
20      */
21     Integer delete(Integer id);
22 
23     /**
24      * 修改
25      * 
26      * @param role
27      * @return
28      */
29     Integer update(Role role);
30 
31     /**
32      * 增加
33      * 
34      * @param role
35      * @return
36      */
37     Integer add(Role role);
38 }
RoleDao 定义

7)创建User,role的映射xml文件,其作用相当于使用JDBC方式进行增删改查时写在数据访问层dao接口实现类里边的sql语句,原来在JDBC方式下增删改是如下这么写的:

技术分享

在mybatis中,在映射接口xml文件中写sql语句,相当于上面的dao接口实现类:

技术分享
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" >
 3 <mapper namespace="cn.smbms.xsh.dao.UserDao">
 4     <select id="getAllUser" resultType="User">
 5         select * from smbms_user
 6     </select>
 7     
 8     <insert id="addUser">
 9             INSERT INTO smbms.smbms_user 
10                 (id, 
11                 userCode, 
12                 userName, 
13                 userPassword, 
14                 gender
15                 )
16                 VALUES
17                 (null, 
18                 #{userCode}, 
19                 #{userName}, 
20                 #{userPassword}, 
21                 #{gender}
22                 );
23     </insert>
24     
25     <update id="update">
26             UPDATE smbms.smbms_user 
27             SET
28             userCode = #{userCode} , 
29             userName = #{userName} , 
30             userPassword = #{userPassword} , 
31             gender = #{gender}  
32             WHERE
33             id = #{id} ;
34     </update>
35 
36     <delete id="delete">
37         delete from smbms_user where id = #{id}
38     </delete>
39 </mapper>
UserDao.xml
技术分享
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" >
 3 <mapper namespace="cn.smbms.xsh.dao.RoleDao">
 4 
 5     <select id="getAll" resultType="Role">
 6         SELECT     id, roleCode, roleName, createdBy, creationDate, 
 7         modifyBy,modifyDate FROM     smbms_role 
 8     </select>
 9     
10     <insert id="add" >
11         INSERT INTO smbms_role 
12         (id, roleCode, roleName, createdBy, creationDate, modifyBy, modifyDate    )
13         VALUES
14         (null,     #{roleCode}, #{roleName}, #{createdBy}, now(), null, null    );
15     </insert>
16     
17     <update id="update">
18         UPDATE smbms.smbms_role 
19         SET
20         roleCode = #{roleCode} , 
21         roleName = #{roleName}, 
22         modifyBy = #{modifyBy} , 
23         modifyDate = now()
24         WHERE
25         id = #{id} 
26     </update>
27     
28     <delete id="delete">
29         delete from smbms_role where id=#{id}
30     </delete>
31     
32 </mapper>
RoleDao.xml

8)mybatis-config.xml配置文件配置:

技术分享
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd" >
 3 <configuration>
 4     <!-- 读取数据库配置文件信息 -->
 5     <properties resource="database.properties">
 6     </properties>
 7     <!-- 配置别名 -->
 8     <typeAliases>
 9         <!-- 通过package, 可以直接指定package的名字, mybatis会自动扫描你指定包下面的javabean, 并且默认设置一个别名,默认的名字为: 
10             javabean 的首字母小写的非限定类名来作为它的别名 -->
11         <package name="cn.smbms.xsh"></package>
12     </typeAliases>
13     <!-- 配置mybatis的多套运行环境,default的值必须是所有environment标签的id属性中的一个值 -->
14     <environments default="development">
15         <environment id="development">
16             <!-- 事务管理方式定义:采用JDBC方式 -->
17             <transactionManager type="JDBC"></transactionManager>
18             <!-- 数据源:采用连接池POOLED -->
19             <dataSource type="POOLED">
20                 <!-- 读取数据库配置文件database.properties里边的数据库配置信息 value获取配置文件中定义的属性的值 -->
21                 <property name="driver" value="${driver}" />
22                 <property name="url" value="${url}" />
23                 <property name="username" value="${user}" />
24                 <property name="password" value="${password}" />
25             </dataSource>
26         </environment>
27     </environments>
28     <!-- 映射接口xml文件的路径,告诉mybatis去哪里找到sql映射文件 -->
29     <mappers>
30         <!-- resource属性的值是sql映射文件的路径 -->
31         <mapper resource="cn/smbms/xsh/dao/RoleDao.xml"></mapper>
32         <mapper resource="cn/smbms/xsh/dao/UserDao.xml"></mapper>
33 
34     </mappers>
35 </configuration>
mybatis-config.xml

database.properties数据库配置文件内容如下:

1 driver=com.mysql.jdbc.Driver
2 url=jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8
3 user=root
4 password=root

 9) 创建Junit TestCase测试类进行测试

技术分享
 1 package cn.smbms.xsh.test;
 2 
 3 import java.io.InputStream;
 4 import java.util.List;
 5 
 6 import org.apache.ibatis.session.SqlSession;
 7 import org.apache.ibatis.session.SqlSessionFactory;
 8 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 9 import org.apache.log4j.Logger;
10 import org.junit.After;
11 import org.junit.Before;
12 import org.junit.Test;
13 
14 import cn.smbms.xsh.dao.UserDao;
15 import cn.smbms.xsh.entity.User;
16 
17 public class UserDaoTest {
18     
19     private Logger logger = Logger.getLogger(UserDaoTest.class);
20     SqlSession sqlSession =null;
21     UserDao dao = null;
22 //@Before 表示每次执行    @Test标签后面的测试方法时,先执行@Before后面的代码
23     @Before
24     public void before(){
25         //mybatis-config.xml配置文件信息读取到输入流中
26         InputStream is = UserDaoTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
27         //创建sqlSessionFactoryBuilder对象
28         SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
29         //创建SqlSessionFactory,也就是sqlSession工厂对象
30         SqlSessionFactory factory = builder.build(is);
31         //开启sqlSession会话
32         sqlSession = factory.openSession();
33         //获取UserDao代理
34         dao = sqlSession.getMapper(UserDao.class);
35     }
36     
37     @Test
38     public void testGetAll(){
39         List<User> userList = dao.getAllUser();
40         for (User user : userList) {
41             logger.debug(user);
42         }
43         
44     }
45     
46     @Test
47     public void testAddUser(){
48         User user = new User();
49         user.setGender(1);
50         user.setUserCode("hanmeimei");
51         user.setUserName("hanmei");
52         user.setUsrePassword("123456");
53 //        user.setId(id);
54         System.out.println(dao.addUser(user));
55         
56     }
57     
58     @Test
59     public void testUpdate(){
60         User user = new User();
61         user.setUserCode("hanmeimei");
62         user.setUserName("韩梅梅");
63         user.setUsrePassword("123456");
64         user.setGender(1);
65         user.setId(16);
66         System.out.println(dao.update(user));
67         
68     }
69     
70     @Test
71     public void testDelete(){
72         System.out.println(dao.delete(16));
73     }
74     
75     @After
76     public void after(){
77         sqlSession.commit();
78         sqlSession.close();
79         System.out.println("over");
80     }
81 
82 }
View Code

 

mybatis学习(一)

标签:家居   lap   incr   tco   配置信息   def   必须   sql_mod   image   

原文地址:http://www.cnblogs.com/enjoyjava/p/7837429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!