1. MyBatis是什么
    MyBatis是一个ORM的数据库持久化框架:对象关系映射
    很多人一看这个概念,一定会想:什么是ORM?什么叫数据库持久化?什么又叫框架?
    MyBatis就是一个解决jdbc做数据库持久化非常麻烦问题的框架,该框架进行了sql方式映射模式orm,让我们在完成数据库持久化的时候更简单。
    1.1.ORM是什么?
    对象关系映射(英语:(Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换 [1] 。从效果上说,它其实是创建了一个可在编程语言里使用的–“虚拟对象数据库”。
    1.2.什么叫数据库持久化?
    数据持久化就是将内存中的数据模型转换为存储模型。
    常见的数据持久有:磁盘持久化和数据库持久化。
    数据库持久化是数据持久化的其中一种,就是把内存中的数据保存到数据库中。
    Java中最简单的就是使用jdbc来完成数据库持久化:

  2. MyBatis的jar包引入

  3. domain的准备

private  Long id;//商品名称private String productName;//品牌private String brand;//供应商private String supplier;//零售价private BigDecimal salePrice;//进价private BigDecimal costPrice;//折扣private Double cutoff;//商品分类编号private Long dir_id;//下面提供get/set

domainMapper.xml (用来装domain对应的sql方法)

<?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的主要功能就是写sqlmapper:根namespace:命令空间 (用来确定唯一) 以前这个是可以不加的,现在必需加namespace的值,规则的:映射文件XxxMapper.xml所在的包+domain类名+Mapper-->
<mapper namespace="cn.shuhan.mybatis.domain.ProductMapper"><!--select : 这里面写查询语句id:用来确定这条sql语句的唯一以后我们确定唯一,也就是找sql语句 : namespace +.+ id例: cn.shuhan.mybatis.domain.ProductMapper.findOneparameterType : 传入的参数类型  long:大Long  _long:小long (具体的对应请参见文档)resultType : 结果类型(第一条数据返回的对象类型) 自己的对象一定是全限定类名--><!-- <select id="findOne" parameterType="long" resultType="cn.shuhan.mybatis.domain.Product">select * from product where id = #{id}</select>--><!--用了别名之后  使用别名--><!--ognl取值: # 和 $ 的区别#是占位符   直接占位是一个?$是拼接数据    会有sql注入问题--><!--查询一个数据方法--><select id="findOne" parameterType="long" resultType="Product">select * from product where id = #{id}</select><!--查询所有数据方法--><select id="findAll" resultType="Product">select * from product</select><!--保存方法--><insert id="save" parameterType="Product">insert into product (productName, dir_id, salePrice, supplier, brand, cutoff, costPrice)values (#{productName}, #{dir_id}, #{salePrice}, #{supplier}, #{brand}, #{cutoff}, #{costPrice})</insert><!--修改方法--><update id="update" parameterType="Product" >update product set productName=#{productName}, dir_id=#{dir_id}, salePrice=#{salePrice},supplier=#{supplier}, brand=#{brand}, cutoff=#{cutoff}, costPrice=#{costPrice}</update><!--删除方法--><delete id="delete" parameterType="long">delete from product where id =#{id}</delete>
</mapper>
  1. 在resources文件夹中配置
  2. mybatis-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><!--引入classpath下的db的配置文件--><properties resource="db.properties"></properties><!--给类型加上别名要加在引入配置文件下   环境搭建上type:原数据类型alias:别名要是不写alias  会默认是类的简单类名  首字母大小写都可以   建议大写 大写一看就知道是一个类先配置别名再使用别名--><typeAliases><!-- <typeAlias type="cn.shuhan.mybatis.domain.Product" alias="product"></typeAlias>--><typeAlias type="cn.shuhan.mybatis.domain.Product" ></typeAlias></typeAliases><!--环境们:多个环境development:开发--><environments default="development"><!--一个环境的配置--><environment id="development"><!--事务的管理:--><transactionManager type="JDBC"/><!--数据源的排至--><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></dataSource></environment></environments><mappers><!--引入写sql语句的mapper配置文件:<mapper resource="org/mybatis/example/BlogMapper.xml"/>--><mapper resource="cn/shuhan/mybatis/domain/ProductMapper.xml"/></mappers>
</configuration>

6.db.properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis
jdbc.username=root
jdbc.password=root

7.log4j.properties配置 需要改的是log4j.logger.cn.shuhan=TRACE 路径改成自己需要生成日志的包路径

log4j.rootLogger=ERROR, stdout
#log4j.rootLogger=NONE
#trace:最详细日志
#debug:调试级别
#info:提示级别
#warnnig:警告级别
#error:错误级别
#级别最高,看到的日志最少:如果打的是TRACE:就可以看到TRACE和以上级别的日志
#如果是ERROR:就只能看到ERROR级别;
#开发测试的时候,日志最好详细点;上线的时候,日志少点,但是关键点:ERROR
#好处:System.out.println:最原始的使用调试信息:开发有很多信息,上线了不应该输出调试信息
#应该删除:很多,不好删;如果不删,会影响性能的.使用log4j:只需要修改日志级别就好了.
#cn.shuhan 是要生成日志的包
log4j.logger.cn.shuhan=TRACElog4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

8.dao持久化层的impl实现

//创建log日志private static final Logger log = LoggerFactory.getLogger(ProductDaoImpl.class);@Overridepublic Product findOne(Long id) {SqlSession sqlSession=null;try {//通过配置文件获得一个ReaderReader reader = Resources.getResourceAsReader("mybatis-config.xml");//获取SqlSessionFactory 对象SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);//获取sqlSessionsqlSession = factory.openSession();//调用sqlSession的api做事情String sql = "cn.shuhan.mybatis.domain.ProductMapper.findOne";//执行sqlreturn sqlSession.selectOne(sql,id);} catch (IOException e) {//用日志输出错误log.error(e.getMessage());e.printStackTrace();return null;} finally {if (sqlSession != null) {sqlSession.close();}}}

9.这儿发现每个方法都要去拿一次sqlsession对象 而每次都去拿sqlsessionFactory对象性能很差 所以抽取一个util工具类

package cn.shuhan.mybatis.util;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 java.io.IOException;
import java.io.Reader;/*** 抽取工具类* 获取SqlSession对象来操作数据库*/
public class MybatisUtil {static SqlSessionFactory factory;static {try {//通过配置文件获得一个ReaderReader reader = Resources.getResourceAsReader("mybatis-config.xml");//获取SqlSessionFactory 对象factory= new SqlSessionFactoryBuilder().build(reader);} catch (IOException e) {e.printStackTrace();}}//提供获取sqlsession的公共方法public static SqlSession getSqlSession(){return factory.openSession();}
}

10.使用了工具类之后的CURD代码如下

package cn.shuhan.mybatis.dao.impl;import cn.shuhan.mybatis.dao.IProductDao;
import cn.shuhan.mybatis.domain.Product;
import cn.shuhan.mybatis.util.MybatisUtil;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.IOException;
import java.io.Reader;
import java.util.List;public class ProductDaoImpl implements IProductDao {//创建log日志private static final Logger log = LoggerFactory.getLogger(ProductDaoImpl.class);//提出公共的sql语句部分 注意有一个点private final String namespace = "cn.shuhan.mybatis.domain.ProductMapper.";@Overridepublic Product findOne(Long id) {SqlSession sqlSession=null;try {//通过配置文件获得一个ReaderReader reader = Resources.getResourceAsReader("mybatis-config.xml");//获取SqlSessionFactory 对象SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);//获取sqlSessionsqlSession = factory.openSession();//调用sqlSession的api做事情String sql = "cn.shuhan.mybatis.domain.ProductMapper.findOne";//执行sqlreturn sqlSession.selectOne(sql,id);} catch (IOException e) {//用日志输出错误log.error(e.getMessage());e.printStackTrace();return null;} finally {if (sqlSession != null) {sqlSession.close();}}}@Overridepublic void save(Product product) {SqlSession sqlSession = null;try {//获取sqlsession对象sqlSession = MybatisUtil.getSqlSession();//调用方法  操作数据库sqlSession.insert(namespace+"save", product);//增删改都要提交事务sqlSession.commit();} catch (Exception e) {e.printStackTrace();} finally {//关闭sqlsessionif (sqlSession != null) {sqlSession.close();}}}@Overridepublic void del(Long id) {SqlSession sqlSession = null;try {sqlSession = MybatisUtil.getSqlSession();sqlSession.delete(namespace+"delete",id);//增删改都要提交事务sqlSession.commit();} catch (Exception e) {e.printStackTrace();} finally {//关闭sqlsessionif (sqlSession != null) {sqlSession.close();}}}@Overridepublic void update(Product product) {SqlSession sqlSession = null;try {sqlSession = MybatisUtil.getSqlSession();sqlSession.update(namespace+"update",product );//增删改都要提交事务sqlSession.commit();} catch (Exception e) {e.printStackTrace();} finally {//关闭sqlsessionif (sqlSession != null) {sqlSession.close();}}}@Overridepublic List<Product> findAll() {log.debug("能不能打印一个");log.info("能不能提示一个");SqlSession sqlSession = null;try {sqlSession = MybatisUtil.getSqlSession();return sqlSession.selectList(namespace+"findAll");} catch (Exception e) {e.printStackTrace();return null;} finally {//关闭sqlsessionif (sqlSession != null) {sqlSession.close();}}}
}

11.接下来就是愉快的测试

package cn.shuhan.mybatis.test;import cn.shuhan.mybatis.dao.IProductDao;
import cn.shuhan.mybatis.dao.impl.ProductDaoImpl;
import cn.shuhan.mybatis.domain.Product;
import org.junit.Test;import java.math.BigDecimal;public class ProductDaoImplTest {private IProductDao productDao = new ProductDaoImpl();@Testpublic void findOne() throws Exception{System.out.println(productDao.findOne(3L));}@Testpublic void save() {//准备数据Product product = new Product();product.setBrand("说什么");product.setCostPrice(new BigDecimal(50));product.setCutoff(0.8);//执行productDao.save(product);}@Testpublic void del() {System.out.println(productDao.findOne(1L));productDao.del(1L);System.out.println(productDao.findOne(1L));}@Testpublic void update() {//先查一个Product product = productDao.findOne(2L);System.out.println(product);product.setCutoff(0.5);product.setCostPrice(new BigDecimal(500));product.setBrand("修改之后 单独");productDao.update(product);System.out.println(productDao.findOne(2L));;}@Testpublic void findAll() {System.out.println(productDao.findAll());}
}

到这儿整个MyBatis的入门就算是ok了

MyBatis入门介绍相关推荐

  1. MyBatis入门介绍,凤凰涅槃:从 iBatis 到 MyBatis

    对于从事 Java EE 的开发人员来说,iBatis 是一个再熟悉不过的持久层框架了,在 Hibernate.JPA 这样的一站式对象 / 关系映射(O/R Mapping)解决方案盛行之前,iBa ...

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

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

  3. MyBatis-学习笔记01【01.Mybatis课程介绍及环境搭建】

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

  4. MyBatis详细介绍

    MyBatis基础入门 内容 1.MyBatis介绍 2.MyBatis入门程序 3.MyBatis使用Mapper接口 4.MyBatis之Config文件常用配置 一.MyBatis简介 1 .简 ...

  5. mybatis入门(七)之日志

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

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

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

  7. JavaWeb——MyBatis入门程序

    一.引言 一般MyBatis与springMVC常常一起使用,而且与hibernate相比有着天然的优势,继续推进. MyBatis应用程序根据XML配置文件创建SqlSessionFactory,S ...

  8. mybatis入门学习之环境的搭建——helloworld

    Mybatis框架环境的搭建 首先,我是一名走java后端的大二菜鸟,我写博客一方面是用来记录我学习中遇到的问题,另一方面是希望和更多的人分享经验.如果我写的内容有不严谨的地方,还请大佬们纠正一下. ...

  9. MyBatis从入门到精通(1):MyBatis入门

    作为一个自学Java的自动化专业211大学本科生,在学习和实践过程中"趟了不少雷",所以有志于建立一个适合同样有热情学习Java技术的参考"排雷手册". 最近在 ...

最新文章

  1. spring in action 4 第5章
  2. Linux-HA开源软件Heartbeat(概念篇)
  3. 汇编中的字符串操作指令
  4. 不同组织间的邮件收发
  5. HDU 2376 Average distance
  6. 最简单的 RabbitMQ 监控方法 - 每天5分钟玩转 OpenStack(158)
  7. 「leetcode」406.根据身高重建队列【贪心算法】详细图解
  8. 正则表达式 - 中文、英文姓名匹配
  9. Android9输入法留白配置,拇指于键盘间游离 2015安卓输入法横评
  10. 以太网驱动的流程浅析(四)-以太网驱动probe流程【原创】
  11. SpringCloud第十章zuul路由网关
  12. java 考勤_java,添加一个类,显示考勤信息的。
  13. python读取手机通讯录_利用python解析手机通讯录
  14. 新人学习opencv图像处理的笔记,一:c++操作图像放大
  15. VCS/Questa SIM 使用流程及Makefile
  16. STM32F103C8T6基础开发教程(HAL库)—开发环境配置
  17. [python之数据分析] 基础篇1- Numpy,Scipy,Matplotlib 快速入门攻略
  18. 手机进行linux编程的 app,手机也能编程?盘点这6个可以用手机编程的App!快收藏...
  19. 比心app源码,html 获取时间
  20. 计算机专业jsp项目,可练手

热门文章

  1. [附源码]Java计算机毕业设计SSM电影票购票系统
  2. 温馨提示:欠谁钱,也别欠阿里云的钱!!!
  3. 2008系统服务器ntp校时,NTP校时服务器(NTP时间服务器)知识普及
  4. listview 排序问题
  5. 设备指纹是一个小型风控系统
  6. 鹰眼瞭望系统属于什么服务器,智慧城轨:描绘更加智能、安全的出行蓝图
  7. 考研数学 第9讲 一元积分的概念
  8. 超级计算机summit存储容量,美国研制世界最强超级计算机Summit,超过神威.太湖...
  9. java中英文汉语混合排序_Android实现列表数据按名称排序、中英文混合排序
  10. c++ sinx的求法