首页 > 代码库 > 05Mybatis_入门程序——根据id查询用户

05Mybatis_入门程序——根据id查询用户

这篇文章我们来做一个入门的案例:

     建表;

技术分享
 1 /* 2 SQLyog v10.2  3 MySQL - 5.1.72-community : Database - mybatis 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 /*Table structure for table `items` */17 18 CREATE TABLE `items` (19   `id` int(11) NOT NULL AUTO_INCREMENT,20   `name` varchar(32) NOT NULL COMMENT ‘商品名称‘,21   `price` float(10,1) NOT NULL COMMENT ‘商品定价‘,22   `detail` text COMMENT ‘商品描述‘,23   `pic` varchar(64) DEFAULT NULL COMMENT ‘商品图片‘,24   `createtime` datetime NOT NULL COMMENT ‘生产日期‘,25   PRIMARY KEY (`id`)26 ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;27 28 /*Table structure for table `orderdetail` */29 30 CREATE TABLE `orderdetail` (31   `id` int(11) NOT NULL AUTO_INCREMENT,32   `orders_id` int(11) NOT NULL COMMENT ‘订单id‘,33   `items_id` int(11) NOT NULL COMMENT ‘商品id‘,34   `items_num` int(11) DEFAULT NULL COMMENT ‘商品购买数量‘,35   PRIMARY KEY (`id`),36   KEY `FK_orderdetail_1` (`orders_id`),37   KEY `FK_orderdetail_2` (`items_id`),38   CONSTRAINT `FK_orderdetail_1` FOREIGN KEY (`orders_id`) REFERENCES `orders` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,39   CONSTRAINT `FK_orderdetail_2` FOREIGN KEY (`items_id`) REFERENCES `items` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION40 ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;41 42 /*Table structure for table `orders` */43 44 CREATE TABLE `orders` (45   `id` int(11) NOT NULL AUTO_INCREMENT,46   `user_id` int(11) NOT NULL COMMENT ‘下单用户id‘,47   `number` varchar(32) NOT NULL COMMENT ‘订单号‘,48   `createtime` datetime NOT NULL COMMENT ‘创建订单时间‘,49   `note` varchar(100) DEFAULT NULL COMMENT ‘备注‘,50   PRIMARY KEY (`id`),51   KEY `FK_orders_1` (`user_id`),52   CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION53 ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;54 55 /*Table structure for table `user` */56 57 CREATE TABLE `user` (58   `id` int(11) NOT NULL AUTO_INCREMENT,59   `username` varchar(32) NOT NULL COMMENT ‘用户名称‘,60   `birthday` date DEFAULT NULL COMMENT ‘生日‘,61   `sex` char(1) DEFAULT NULL COMMENT ‘性别‘,62   `address` varchar(256) DEFAULT NULL COMMENT ‘地址‘,63   PRIMARY KEY (`id`)64 ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;65 66 /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;67 /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;68 /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;69 /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
sql_table
技术分享
 1 /* 2 SQLyog v10.2  3 MySQL - 5.1.72-community : Database - mybatis 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 /*Data for the table `items` */17 18 insert  into `items`(`id`,`name`,`price`,`detail`,`pic`,`createtime`) values (1,‘台式机‘,3000.0,‘该电脑质量非常好!!!!‘,NULL,‘2015-02-03 13:22:53‘),(2,‘笔记本‘,6000.0,‘笔记本性能好,质量好!!!!!‘,NULL,‘2015-02-09 13:22:57‘),(3,‘背包‘,200.0,‘名牌背包,容量大质量好!!!!‘,NULL,‘2015-02-06 13:23:02‘);19 20 /*Data for the table `orderdetail` */21 22 insert  into `orderdetail`(`id`,`orders_id`,`items_id`,`items_num`) values (1,3,1,1),(2,3,2,3),(3,4,3,4),(4,4,2,3);23 24 /*Data for the table `orders` */25 26 insert  into `orders`(`id`,`user_id`,`number`,`createtime`,`note`) values (3,1,‘1000010‘,‘2015-02-04 13:22:35‘,NULL),(4,1,‘1000011‘,‘2015-02-03 13:22:41‘,NULL),(5,10,‘1000012‘,‘2015-02-12 16:13:23‘,NULL);27 28 /*Data for the table `user` */29 30 insert  into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (1,‘王五‘,NULL,‘2‘,NULL),(10,‘张三‘,‘2014-07-10‘,‘1‘,‘北京市‘),(16,‘张小明‘,NULL,‘1‘,‘河南郑州‘),(22,‘陈小明‘,NULL,‘1‘,‘河南郑州‘),(24,‘张三丰‘,NULL,‘1‘,‘河南郑州‘),(25,‘陈小明‘,NULL,‘1‘,‘河南郑州‘),(26,‘王五‘,NULL,NULL,NULL);31 32 /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;33 /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;34 /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;35 /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
sql_data

技术分享

给出案例结构:

             技术分享

 

 

第一步:编写po类:User.java

 1 package cn.itcast.mybatis.po; 2  3 import java.util.Date; 4  5 public class User { 6 private int id;//主键 7 private String username;//用户的名称 8 private Date birthday;//生日 9 private String sex;//性别10 private String address;//地址11 public int getId() {12     return id;13 }14 public void setId(int id) {15     this.id = id;16 }17 public String getUsername() {18     return username;19 }20 public void setUsername(String username) {21     this.username = username;22 }23 public Date getBirthday() {24     return birthday;25 }26 public void setBirthday(Date birthday) {27     this.birthday = birthday;28 }29 public String getSex() {30     return sex;31 }32 public void setSex(String sex) {33     this.sex = sex;34 }35 public String getAddress() {36     return address;37 }38 public void setAddress(String address) {39     this.address = address;40 }41 42 }

第二步:编写config包下面的SqlMapConfig.xml。这个配置文件主要是配置mybaits运行环境,数据源,事务等。SqlMapConfig.xml代码如下:

 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6     <!-- 和spring整合后 environments配置将废除--> 7     <environments default="development"> 8         <environment id="development"> 9         <!-- 使用jdbc事务管理-->10             <transactionManager type="JDBC" />11         <!-- 数据库连接池-->12             <dataSource type="POOLED">13                 <property name="driver" value="com.mysql.jdbc.Driver" />14                 <property name="url" value="jdbc:mysql://localhost:3306/mybaits?characterEncoding=utf-8" />15                 <property name="username" value="root" />16                 <property name="password" value="root" />17             </dataSource>18         </environment>19     </environments>20     21     <!-- 把映射文件(sqlmap/user.xml)加载进sqlMapConfig.xml-->22         <mappers>23         <mapper resource="sqlmap/user.xml"/>24          </mappers>25     26 </configuration>

第三步:编写映射文件sqlmap/user.xml

 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <!-- nanmespace:命名空间。 作用就是对sql进行分类话管理,理解Sal分离 6  7 注意:使用mapper代理方式,namespace有特殊重要的作用 8 --> 9 10 <mapper namespace="test">11     12     <!-- 根据id获取用户信息 -->13     <!-- 在映射文件中配置很多sql语句 -->14     <!-- 15     id:标识映射文件中的sql;16     将sql语句封装到mappedStatement对象中,所以将id称为statement的id;parmenterType:指定输入的参数的类型,这里指定的int型17     #{}表示一个占位符号;18     #{id}:其中的id表示接收输入的参数,参数名称就是id,如果输入参数就是简单类型,#{}中的参数名可以任意,可以value或其它名称19     resultType:指定的sql输出结果的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象;20     21      -->22     <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">23         select * from user where id = #{id}24     </select>25     <!-- 自定义条件查询用户列表 -->26     <select id="findUserByUsername" parameterType="java.lang.String" 27             resultType="cn.itcast.mybatis.po.User">28        select * from user where username like ‘%${value}%‘ 29     </select>30     31 </mapper>

第四步:编写日志文件(log4j.properties)和Junit测试程序:

log4j.properties文件源码:

1
2
3
4
5
6
7
# Global logging configuration
#\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216error
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

Junit测试程序源码:

 1 package cn.itcast.mybatis.first; 2  3 import java.io.IOException; 4 import java.io.InputStream; 5  6 import org.apache.ibatis.io.Resources; 7 import org.apache.ibatis.session.SqlSession; 8 import org.apache.ibatis.session.SqlSessionFactory; 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;10 import org.junit.Before;11 import org.junit.Test;12 13 import cn.itcast.mybatis.po.User;14 15 public class Mybatis_first {16     17     //会话工厂18     private SqlSessionFactory sqlSessionFactory;19     //这些事必备的,所以放在Before这里了20     @Before21     public void createsqlSessionFactory() throws IOException22     {23         //配置文件24         String resource="SqlMapConfig.xml";25         InputStream inputStream=Resources.getResourceAsStream(resource);26         //使用SqlSessionFactoryBuilder从配置文件中创建SqlSessionFactory.27         sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);28     }29     @Test30 //根据id查询用户的信息31     public void testFindUseById()32     {    //数据库会话实例33         SqlSession sqlSession=null;34         try {35         36             //创建数据库会话实例sqlSession;37             sqlSession=sqlSessionFactory.openSession();38             39             User user=sqlSession.selectOne("test.findUserById", 10);40  //输出对象的hashcode41             System.out.println(user);42         } catch (Exception e) {43             44             e.printStackTrace();45         }46         finally{47             //如果sqlSession实例是创建的那么把他关闭掉48             if(sqlSession!=null)49             {sqlSession.close();50                 51             }                         52         }           53     }       54 }

运行结果:成功了,

输出为:cn.itcast.mybatis.po.User@4c1bd4f6

 


来源: 传智播客

05Mybatis_入门程序——根据id查询用户