MyBatis学习一:环境搭建与第一个Demo

1. 回顾JDBC编程步骤

  1. 加载数据库驱动

  2. 创建并获取数据库链接

  3. 创建jdbc PreparedStatement对象

  4. 定义sql语句

  5. 设置sql语句中的参数(使用PreparedStatement)

  6. 通过statement执行sql并获取结果

  7. 对sql执行结果进行解析处理

  8. 释放资源(ResultSet、PreparedStatement、Connection)


2. 问题总结

  1. 数据库连接,使用时就创建,不使用立即释放,对数据库进行频繁连接开启和关闭,造成数据库资源浪费,影响数据库性能。

设想:使用数据库连接池管理数据库连接。

  1. 将sql语句硬编码到Java代码中,如果sql语句修改,需要重新编译Java代码,不利于系统维护。

设想:将sql语句配置在xml配置文件中,即使sql变化,不需要对Java代码进行重新编译。

3)向preparedStatement中设置参数,对占位符号位置和设置参数值,硬编码在Java代码中,不利于系统维护。

设想:将sql语句及占位符号和参数全部配置在xml中。

  1. 从resultSet中遍历结果集数据时,存在硬编码,将获取表的字段进行硬编码,不利于系统维护。

设想:将查询的结果集,自动映射成Java对象。


3. 引入MyBatis

(1)Mybatis 介绍

  1. Mybatis是一个持久层的框架,是apache下的顶级项目。

  2. Mybatis托管到goolecode下,再后来托管到github下

  3. Mybatis让程序将主要精力放在sql上,通过Mybatis提供的映射方式,自由灵活生成(半自动化,大部分需要程序员编写sql)满足需要sql语句。

  4. Mybatis可以将向 PreparedStatement中的输入参数自动进行输入映射,将查询结果集灵活映射成java对象。(输出映射)

MyBatis官方文档:https://mybatis.org/mybatis-3/

MyBatis GitHub下载:https://github.com/mybatis/mybatis-3

(2)ORM

ORM :Object Relational Mapping 对象关联映射

对象关系映射即是将Java中的对象一一对应映射到数据库的Table(表)中,通过对对象各个属性赋值来更新数据库。官方的说,对象关系映射(Object Relational Mapping,简称ORM)是通过使用描述对象和数据库之间映射的元数据,将面向对象语言程序中的对象自动持久化到关系数据库中。


Java                                            MySQL

Object                                         Data

一个个对象                                    一条条记录

用于实现面向对象编程语言里不同类型系统的数据之间的转换。从效果上说,它其实是创建了一个可在编程语言里使用的--“虚拟对象数据库”。

ORM只是 对象关联映射 设计思想,具体技术: Mybatis 、Hibernate


(3)第一个Mybatis环境搭建

(1)新建Java项目,导入mybatis 、mysql-connector-java 相关依赖

(2)数据源配置 mybatis-config.xml

(3)实体类 pojo 

(4)dao 接口

(5)映射文件mapper

(6)MybatisUtil类设计

(7)测试

(3.1)maven 导入相关依赖

<!--=================依赖========================-->
  <dependencies>
    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.33</version>
    </dependency>

    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.0</version>
    </dependency> 
  
  </dependencies>

说明:

mybatis-config.xml: 从mybatis框架下载的源码中获取,复制到项目中

是Mybatis 核心配置文件: 配置了数据源、连接池、映射mapper文件等

(3.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">

<!--Mybatis 核心配置文件:配置了数据源、连接池、映射mapper文件 -->

<configuration>

    <environments default="development">

        <environment id="development">

            <transactionManager type="JDBC">

                <property name="" value=""/>

            </transactionManager>

            <dataSource type="UNPOOLED">

                <property name="driver" value="com.mysql.jdbc.Driver"/>

                <property name="url" value="jdbc:hsqldb:mem:automapping"/>

                <property name="username" value="root"/>

            </dataSource>

        </environment>

    </environments>

<!-- 注册mapper文件到mybatis-config.xml中-->

  <mappers>

    <mapper resource="com/aistar/dao/CustomerMapper.xml" />

  </mappers>

</configuration>

(3.2)定义dao接口

public interface CustomerDao {
    /**
     * 根据主键查询用户对象
     * @param id 指定查询的用户id
     * @return  返回对应的Customer对象
     */
    public Customer selectById(int id);
}

(3.3) Customer.java POJO类省略

(3.4) CustomerMapper.xml ( mybatis框架下载的源码中获取,复制到项目中 )

定义了执行sql语句,结果映射(数据库表中记录与java中对象的映射关系)

<?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: dao接口的类全名
-->
<mapper namespace="com.aistar.dao.CustomerDao">

   <resultMap id="customer" type="com.aistar.entity.Customer">
      <!--主键列 映射 id -->
      <id column="cust_id" property="custId"></id>
      <result column="cust_name" property="custName"></result>
      <result column="cust_pwd" property="custPwd"></result>
      <result column="cust_gender" property="custGender"></result>
      <result column="cust_telno" property="custTelno"></result>
      <result column="cust_email" property="custEmail"></result>
   </resultMap>

   <!--
      根据主键查询用户对象
      id:dao接口方法名
      parameterType: 方法的参数类型
      resultType: (类类型、基本数据类型)方法返回值类型
      resultMap: 返回的是自定义好的<resultMap id="">
    -->
   <select id="selectById" parameterType="int" resultMap="customer">
      select cust_id,cust_name,cust_pwd, cust_gender,cust_telno, cust_email
       from customer
       where cust_id = #{id} and cust_status =0
   </select>

</mapper>

(3.5)MybatisUtil.java

/**
 * 获得SqlSession与关闭SqlSession
 */
public class MyBatisUtil {
    private static SqlSession sqlSession;
    private static   SqlSessionFactory sqlSessionFactory;

   static {
       //将mybatis-config.xml(还包含mapper.xml)加载到读取流中
       InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream("config/mybatis-config.xml");
        System.out.println(is);
        //读取mybatis-config.xml的数据源信息,建立数据库连接
       sqlSessionFactory =  new  SqlSessionFactoryBuilder().build(is);

   }

    /**
     * SqlSession : 一级缓存 ,管理数据库的sql语句操作(增删改查操作),封装的是PreparedStatement
     * @return 返回SqlSession对象
     */
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

    /**
     * 关闭SqlSession
     */
    public static void closeSqlSession(){
        if(sqlSession!=null ){
            sqlSession.close();
        }
    }

}

(3.6)测试类

public class TestCustomer {
    public static void main(String[] args) {
              
        CustomerDao dao = MyBatisUtil.getSqlSession().getMapper(com.aistar.dao.CustomerDao.class);
        Customer customer = dao.selectById(101);
        System.out.println(customer);
    }
}

分析:

    mybatis-config.xml:
        <mappers>
        <mapper resource="com/aistar/dao/CustomerMapper.xml" />
        <mapper resource="com/aistar/dao/NoteMapper.xml" />
        <mapper resource="com/aistar/dao/TraceMapper.xml" />
        <mapper resource="com/aistar/dao/CommentMapper.xml" />
     </mappers>
     
    1. 
         mapper文件注册到mybatis-config.xml 中心
         注册:CustomerMapper.xml 【namespace="com.aistar.dao.CustomerDao"】
         注册:NoteMapper.xml     【namespace="com.aistar.dao.NoteDao"】
    
    2. Statement Collection 容器
        namespace ="接口类全名1 com.aistar.dao.CustomerDao"
            <select id="接口的方法名">
            <insert id="接口的方法名">
            <update id="接口的方法名">
            <delete id="接口的方法名">
            <....   id="接口的方法名">
            
         namespace ="接口类全名2 com.aistar.dao.NoteDao"
            <select id="接口的方法名">
            <insert id="接口的方法名">
            <update id="接口的方法名">
            <delete id="接口的方法名">
            <....   id="接口的方法名">
  1. getMapper :底层产生一个CustomerDao代理对象(是CustomerDao的实现子类),CustomerDaoImplProxy到注册中心 mybatis-config.xml 找对应namespace文件中的

  2. dao.selectById(..):CustomerDaoImplProxy 到Statement Collection 对应 namespace 有没有匹配的id与当前方法同名,
    sqlSession封装了 PreparedStatement.executeQuery( <select id="接口的方法名"> 转换成sql语句)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容