MyBatis是什么

MyBatis是什么,MyBatis的jar包中有它的官方文档,文档是这么描述MyBatis的:

MyBatis is a first class persistence framework with support for custom SQL, stored procedures
and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of
parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration
and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.

翻译过来就是:MyBatis是一款支持普通SQL查询、存储过程和高级映射的持久层框架。MyBatis消除了几乎所有的JDBC代码、参数的设置和结果集的检索。MyBatis可以使用简单的XML或注解用于参数配置和原始映射,将接口和Java POJO(普通Java对象)映射成数据库中的记录。

本文先入门地搭建表、建立实体类、写基础的配置文件、写简单的Java类,从数据库中查出数据,深入的内容后面的文章再逐一研究。

建表、建立实体类

从简单表开始研究MyBatis,所以我们先建立一张简单的表:

create table student
(studentId          int                        primary key     auto_increment    not null,studentName        varchar(20)                                                  not null,studentAge         int                                                          not null,studentPhone       varchar(20)                                                  not null
)charset=utf8insert into student values(null, 'Jack', 20, '000000');
insert into student values(null, 'Mark', 21, '111111');
insert into student values(null, 'Lily', 22, '222222');
insert into student values(null, 'Lucy', 23, '333333');
commit;

一个名为student的表格,里面存放了student相关字段,当然此时我们需要有一个Java实体类与之对应:

public class Student
{private int        studentId;private String     studentName;private int        studentAge;private String    studentPhone;public Student(){super();}public Student(int studentId, String studentName, int studentAge,String studentPhone){this.studentId = studentId;this.studentName = studentName;this.studentAge = studentAge;this.studentPhone = studentPhone;}public int getStudentId(){return studentId;}public void setStudentId(int studentId){this.studentId = studentId;}public String getStudentName(){return studentName;}public void setStudentName(String studentName){this.studentName = studentName;}public int getStudentAge(){return studentAge;}public void setStudentAge(int studentAge){this.studentAge = studentAge;}public String getStudentPhone(){return studentPhone;}public void setStudentPhone(String studentPhone){this.studentPhone = studentPhone;}public String toString(){return "StudentId:" + studentId + "\tStudentName:" + studentName + "\tStudentAge:" + studentAge + "\tStudentPhone:" + studentAge;}
}

注意,这里空构造方法必须要有,SqlSession的selectOne方法查询一条信息的时候会调用空构造方法去实例化一个domain出来。OK,这样student表及其对应的实体类Student.java就创建好了。

写config.xml文件

在写SQL语句之前,首先得有SQL运行环境,因此第一步是配置SQL运行的环境。创建一个Java工程,右键src文件夹,创建一个普通文件,取个名字叫做config.xml,config.xml里这么写:

<?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><typeAliases><typeAlias alias="Student" type="com.xrq.domain.Student"/></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/test"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments><mappers><mapper resource="student.xml"/></mappers>
</configuration>

这就是一个最简单的config.xml的写法。接着右键src,创建一个普通文件,命名为student.xml,和mapper里面的一致(resource没有任何的路径则表示student.xml和config.xml同路径),student.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"><mapper namespace="com.xrq.StudentMapper"><select id="selectStudentById" parameterType="int" resultType="Student"><![CDATA[select * from student where studentId = #{id}]]></select>
</mapper>

专门有一个student.xml表示student表的sql语句,当然也可以几张表共用一个.xml文件,这个看自己的项目和个人喜好。至此,MyBatis需要的两个.xml文件都已经建立好,接下来需要做的就是写Java代码了。

Java代码实现

首先要进入MyBatis的jar包:

第二个MySql-JDBC的jar包注意一下要引入,这个很容易忘记。

接着创建一个类,我起名字叫做StudentOperator,由于这种操作数据库的类被调用频繁但是调用者之间又不存在数据共享的问题,因此使用单例会比较节省资源。为了好看,写一个父类BaseOperator,SqlSessionFactory和Reader都定义在父类里面,子类去继承这个父类:

public class BaseOperator
{protected static SqlSessionFactory ssf;protected static Reader reader;static{try{reader = Resources.getResourceAsReader("config.xml");ssf = new SqlSessionFactoryBuilder().build(reader);} catch (IOException e){e.printStackTrace();}}
}

然后创建子类StudentOperator:

public class StudentOperator extends BaseOperator
{private static StudentOperator instance = new StudentOperator();private StudentOperator(){}public static StudentOperator getInstance(){return instance;}public Student selectStudentById(int studentId){SqlSession ss = ssf.openSession();Student student = null;try{student = ss.selectOne("com.xrq.StudentMapper.selectStudentById", 1);}finally{ss.close();}return student;}
}

这个类里面做了两件事情:

1、构造一个StudentOperator的单实例

2、写一个方法根据studentId查询出一个指定的Student

验证

至此,所有步骤全部就绪,接着写一个类来验证一下:

public class MyBatisTest
{public static void main(String[] args){System.out.println(StudentOperator.getInstance().selectStudentById(1));}
}

运行结果为:

StudentId:1    StudentName:Jack    StudentAge:20    StudentPhone:20

看一下数据库中的数据:

数据一致,说明以上的步骤都OK,MyBatis入门完成,后面的章节,将会针对MyBatis的使用细节分别进行研究。

from: http://www.cnblogs.com/xrq730/p/5254301.html

MyBatis1:MyBatis入门相关推荐

  1. Mybatis入门之动态sql

    Mybatis入门之动态sql 通过mybatis提供的各种标签方法实现动态拼接sql. 1.if.where.sql.include标签(条件.sql片段) <sql id="sel ...

  2. MyBatis(1):MyBatis入门

    MyBatis是什么 MyBatis是什么,MyBatis的jar包中有它的官方文档,文档是这么描述MyBatis的: MyBatis is a first class persistence fra ...

  3. MyBatis-学习笔记02【02.Mybatis入门案例】

    Java后端 学习路线 笔记汇总表[黑马程序员] MyBatis-学习笔记01[01.Mybatis课程介绍及环境搭建][day01] MyBatis-学习笔记02[02.Mybatis入门案例] M ...

  4. mybatis入门(七)之日志

    转载自    mybatis入门(七)之日志 Mybatis 的内置日志工厂提供日志功能,内置日志工厂将日志交给以下其中一种工具作代理: SLF4J Apache Commons Logging Lo ...

  5. mybatis入门(一)之基础安装

    转载自  mybatis入门 安装 要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于 classpath 中即可. 如果使用 Maven 来构建项目,则需将下面的 dep ...

  6. Mybatis入门程序增删改查操作

    学习目标 了解Mybatis的基本知识 熟悉Mybatis的工作原理 掌握Mybatis入门程序的编写 文章目录 1.初始Mybatis 2.Mybatis入门程序 3.Mybatis操作总结 1.初 ...

  7. Mybatis入门 使用注解

    使用XML方式地址为Mybatis入门 使用XML 1.目录结构 2.需要修改的地方 1.mybatis的配置文件 <?xml version="1.0" encoding= ...

  8. Mybatis入门 使用XML

    1.项目结构 2.详细代码 数据库: 1.创建实体类bean package com.itheima.domain;import java.io.Serializable; import java.u ...

  9. MyBatis入门(二)---一对一,一对多

    一.创建数据库表 1.1.创建数据表同时插入数据 /* SQLyog Enterprise v12.09 (64 bit) MySQL - 5.6.27-log : Database - mybati ...

最新文章

  1. 半世纪全球顶级学者迁移图(附视频、亿级学术信息)| 数据院科技大数据研究中心发布
  2. 组合查询——怎样使用窗口的继承达到事半功倍?
  3. mysql my.cnf key_buffer_size_优化mysql之key_buffer_size设置
  4. Win10系列:JavaScript页面导航
  5. $(document).ready()和window.onload之间的差异
  6. 我们为什么活得这么累
  7. LINUX用C检查文件的大小的代码
  8. xshell远程登录工具的星号密码查看方法
  9. 微信 获取 用户信息访问授权管理
  10. python爬虫selenium和bs4_python爬虫――selenium+bs4爬取选股宝‘利好‘or’利空'股票信息...
  11. 关于在工作中遇到的问题及解决方案
  12. 使用 Mac 位置定位服务的应用的操作方法
  13. 基于IjkPlayer的多路投屏直播
  14. Electron 打包Mac安装包代码签名问题解决方案
  15. Tkinter Treeview tag_configure失效问题
  16. 多媒体计算机维修记载,多媒体教学计划(精选3篇)
  17. ubuntu1804系统设置在哪里_ubuntu1804安装后设置
  18. 聊天机器人应用趋势跟踪月报
  19. Deepin系统卸载alsa-base后导致系统无法启动
  20. function Function 区别

热门文章

  1. Redis数据持久化机制AOF原理分析一---转
  2. XGBoost的基本使用应用Kaggle便利店销量预测
  3. Gartner 2015新兴技术发展周期简评:大数据实用化、机器学习崛起
  4. GDB中应该知道的几个调试方法
  5. Spring Cloud Alibaba - 26 Gateway-自定义谓词工厂RoutePredicateFactory
  6. 深入理解分布式技术 - 分布式缓存实战_常见的坑及解决办法
  7. Java8 - 使用CompletableFuture 构建异步应用
  8. 并发编程-16AQS同步组件之CountDownLatch 闭锁
  9. Quartz-JobDataMap 参数传递
  10. 打印杨辉三角形知识点_用编程方法打印杨辉三角形