欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mybatis学习记录------1

程序员文章站 2024-01-25 20:27:04
一 认识mybatis mybatis是一个优秀的数据持久层框架,在实体类和SQL语句之间建立映射关系,是一种半自动化的ORM(对象,关系映射)实现。其封装性要低于Hibernate,性能优越,并且小巧、简单易学,应用也越来越广泛。 二 搭建mybatis环境 1.下载需要的JAR包 2.部署jar ......

一 认识mybatis

mybatis是一个优秀的数据持久层框架,在实体类和sql语句之间建立映射关系,是一种半自动化的orm(对象,关系映射)实现。其封装性要低于hibernate,性能优越,并且小巧、简单易学,应用也越来越广泛。

二 搭建mybatis环境

1.下载需要的jar包

mybatis学习记录------1

2.部署jar文件

将上述下载的jar文件部署到项目内

三 日志配置

在java resources下新建resource文件,命名config,此时config文件夹和src文件夹是一样的。

在config文件夹下新建log4j.properties文件

 

 并且输入如下代码(可上jar包附带的pdf文档内查看)

# global logging configuration
#log4j.rootlogger=error, stdout
log4j.rootlogger=debug, stdout
# mybatis logging configuration...
log4j.logger.org.mybatis.example.blogmapper=trace
# 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

四 工程架构

结构:

mybatis学习记录------1

数据库:mysql

create schema `mybatis` default character set utf8 ;
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;

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;

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;

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;





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');
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);
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);
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);

 

 

1.在config文件夹下新建sqlmapconfig.xml(mybatis核心配置文件)

配置mybatis的运行环境,数据源,事务等

<?xml version="1.0" encoding="utf-8"?>
<!doctype configuration
public "-//mybatis.org//dtd config 3.0//en"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionmanager type="jdbc"/>
      <datasource type="pooled">
        <property name="driver" value="com.mysql.jdbc.driver"/><!-- ${driver} -->
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterencoding=utf-8"/><!-- ${url} -->
        <property name="username" value="root"/><!-- ${username} -->
        <property name="password" value="123456"/><!-- ${password} -->
      </datasource>
    </environment>
  </environments>
</configuration>

 

2.创建持久化类pojo

持久化类是指其实例对象需要被mybatis持久化到数据库中的类。在应用的设计中,持久化类通常对应需求中的业务实体,mybatis中一般采用pojo编程模型来实现持久化类。

在src文件夹下新建po包

mybatis学习记录------1

在po包下新建user.java

package pers.czs.mybatis.po;

import java.util.date;

public class user {
    //属性名和数据库中字段对应
    private int id;
    private string username;// 用户姓名
    private string sex;// 性别
    private date birthday;// 生日
    private string address;// 地址
    public int getid() {
        return id;
    }
    public void setid(int id) {
        this.id = id;
    }
    public string getusername() {
        return username;
    }
    public void setusername(string username) {
        this.username = username;
    }
    public string getsex() {
        return sex;
    }
    public void setsex(string sex) {
        this.sex = sex;
    }
    public date getbirthday() {
        return birthday;
    }
    public void setbirthday(date birthday) {
        this.birthday = birthday;
    }
    public string getaddress() {
        return address;
    }
    public void setaddress(string address) {
        this.address = address;
    }
    
}

 

3.映射文件

映射文件命名:

mapper代理开发映射文件名称叫做xxxmapper.xml,比如:usermapper.xml

在config文件夹下新建folder,命名为sqlmap(存放映射文件)

在sqlmap下新建user.xml

<?xml version="1.0" encoding="utf-8"?>
<!doctype mapper
public "-//mybatis.org//dtd mapper 3.0//en"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespace 命名空间,作用是对sql进行分类化管理,理解为对sql进行隔离 -->
<mapper namespace="test">
    <!-- 在映射文件中配置很多sql语句 -->
    <!-- 
        通过select执行数据库查询
        id:标识映射文件中的sql,
        将sql语句封装到mappedstatement对象中
         parametertype表示指定输入参数类型,这里指定int型
         #{}表示一个占位符,和jdbc内的?一样
         #{id}:其中的id表示接收输入的参数,参数名称就是id,如果输入参数时简单类型,那么#{}中的参数名可以任意
         resulttype:指定sql输出结果所映射的java对象类型,select指定resulttype表示将单条记录映射成的java对象。
     -->
     
     <select id="finduserbyid" parametertype="int" resulttype="pers.czs.mybatis.po.user">
         select * from user where id=#{id}
     </select>
</mapper>

4.在sqlmapconfig文件中加载配置文件

mybatis学习记录------1

五 程序编写

1.在src内新建first包用于测试

mybatis学习记录------1

在包内新建mybatisfirst.java文件

package pers.czs.mybatis.first;

import java.io.ioexception;
import java.io.inputstream;

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.test;

import pers.czs.mybatis.po.user;

public class mybatisfirst {
    //根据id查询用户信息,得到一条记录的结果
    @test
    public void finduserbyidtest() throws ioexception {
        
        //mybatis配置文件
        string resource = "sqlmapconfig.xml";
        //得到配置文件流
        inputstream inputstream = resources.getresourceasstream(resource);
        
        //创建会话工厂,传入配置文件信息
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(inputstream);
        //通过工厂得到sqlsession会话
        sqlsession sqlsession = sqlsessionfactory.opensession();
        
        //通过sqlsession操作数据库
        //第一个参数:映射文件中的id,等于namespace+"."+id 
        //第二个参数:指定和映射文件中所匹配的parametertype类型的参数
        //sqlsession.selectone的结果是与映射文件中所匹配的resulttype类型的对象
        user user = sqlsession.selectone("test.finduserbyid", 1);
        system.out.println(user+"  这是输出结果");
        //释放资源
        sqlsession.close();
    }
}

 

2.junit运行

运行结果:

mybatis学习记录------1

其中debug[main]是运行日志