6-MyBatis基础

1-MyBatis概述

1-1-介绍

 MyBatis(前身是iBatis)是一个支持普通SQL查询、存储过程以及高级映射的持久层框架。

MyBatis框架也被称之为ORM(Object/Relation Mapping,即对象关系映射)框架。

所谓的ORM就是一种为了解决面向对象与关系型数据库中数据类型不匹配的技术,它通过描述Java对象与数据库表之间的映射关系,自动将Java应用程序中的对象持久化到关系型数据库的表中。

1-2-ORM框架的工作原理

1-3-Hibernate与MyBatis有什么区别

Hibernate是一个全表映射的框架。
通常开发者只需定义好持久化对象到数据库表的映射关系,就可以通过Hibernate提供的方法完成持久层操作。
开发者并不需要熟练的掌握SQL语句的编写,Hibernate会根据制定的存储逻辑,自动的生成对应的SQL,并调用JDBC接口来执行,所以其开发效率会高于MyBatis。
Hibernate也存在一些缺点,例如它在多表关联时,对SQL查询的支持较差;更新数据时,需要发送所有字段;不支持存储过程;不能通过优化SQL来优化性能等。

MyBatis是一个半自动映射的框架。
“半自动”是相对于Hibernate全表映射而言的,MyBatis需要手动匹配提供POJO、SQL和映射关系,而Hibernate只需提供POJO和映射关系即可。
与Hibernate相比,虽然使用MyBatis手动编写SQL要比使用Hibernate的工作量大,但MyBatis可以配置动态SQL并优化SQL,可以通过配置决定SQL的映射规则,它还支持存储过程等。对于一些复杂的和需要优化性能的项目来说,显然使用MyBatis更加合适。

2-MyBatis的下载和使用

下载地址:https://github.com/mybatis/mybatis-3/releases

使用MyBatis框架非常简单,只需在应用程序中引入MyBatis的核心包和lib目录中的依赖包即可。

注意:如果底层采用的是MySQL数据库,那么还需要将MySQL数据库的驱动JAR包添加到应用程序的类路径中;

如果采用其他类型的数据库,则同样需要将对应类型的数据库驱动包添加到应用程序的类路径中。

3-MyBatis的工作原理

4-MyBatis入门程序

4-1-创建数据库和表

MySQL数据库中,创建一个名为mybatis的数据库,在此数据库中创建一个t_customer表,同时预先插入几条数据。

CREATE DATABASE `mybatis`;

USE `mybatis`;

CREATE TABLE `t_customer` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `jobs` varchar(50) DEFAULT NULL,
  `phone` varchar(16) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ;

insert  into `t_customer`(`id`,`username`,`jobs`,`phone`) values (1,'joy','doctor','13756566565'),(2,'jack','teacher','13645455454'),(3,'tom','worker','13423233232');

4-2-创建项目等准备工作

1.在Eclipse中,创建一个名为chapter06的Web项目,将MyBatis的核心JAR包、lib目录中的依赖JAR包,以及MySQL数据库的驱动JAR包一同添加到项目的lib目录下, 并发布到类路径中。

2.由于MyBatis默认使用log4j输出日志信息,所以如果要查看控制台的输出SQL语句,那么就需要在classpath路径下配置其日志文件。在项目的src目录下创建log4j.properties文件。

       # Global logging configuration
       log4j.rootLogger=ERROR, stdout
       # MyBatis logging configuration...
       log4j.logger.com.itheima=DEBUG
       # 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

3.在src目录下,创建一个com.itheima.po包,在该包下创建持久化类Customer,并在类中声明id、username、jobs和phone属性,及其对应的getter/setter方法。

public class Customer {
            private Integer id;        
            private String username;  
            private String jobs;       
            private String phone
            //省略Getter和Setter方法
            @Override
             public String toString() {
         return "Customer [id=" + id + ", username=" + username +
                      ", jobs=" + jobs + ", phone=" + phone + "]";
    }
     }

 

 

4-3-查询客户

4-3-1-根据客户编号查询客户信息

根据客户编号查询客户信息主要是通过查询客户表中的主键(这里表示唯一的客户编号)来实现的。

1.在src目录下,创建一个com.itheima.mapper包,并在包中创建映射文件CustomerMapper.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.itheima.mapper.CustomerMapper">
    <select id="findCustomerById" parameterType="Integer"
        resultType="com.itheima.po.Customer">
        select * from t_customer where id = #{id}
    </select>
       </mapper>

2.在src目录下,创建MyBatis的核心配置文件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>
              <environments default="mysql">
                     <environment id="mysql">
                           <transactionManager type="JDBC" />
                               <dataSource type="POOLED">
                      <property name="driver" value="com.mysql.jdbc.Driver" />
                                  <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC" />              
                      <property name="username" value="root" />
                      <property name="password" value="root" />
                                </dataSource>
                           </environment>
                      </environments>
             <mappers>
         <mapper resource="com/itheima/mapper/CustomerMapper.xml" />
             </mappers>
        </configuration>


3.在src目录下,创建一个com.itheima.test包,在该包下创建测试类MybatisTest,并在类中编写测试方法findCustomerByIdTest()。

public class MybatisTest {
             @Test
             public void findCustomerByIdTest() throws Exception {                             
                     String resource = "mybatis-config.xml";
         InputStream inputStream = Resources.getResourceAsStream(resource);
                     SqlSessionFactory sqlSessionFactory =
                                       new SqlSessionFactoryBuilder().build(inputStream);     
                     SqlSession sqlSession = sqlSessionFactory.openSession();
         Customer customer = sqlSession.selectOne("com.itheima.mapper"
                    + ".CustomerMapper.findCustomerById", 1);         

System.out.println(customer.toString());
         sqlSession.close();
             }
     }

 

4-3-2-根据客户名模糊查询客户信息。

模糊查询的实现非常简单,只需在映射文件中通过<select>元素编写相应的SQL语句

1.在映射文件CustomerMapper.xml中,添加根据客户名模糊查询客户信息列表的SQL语句。

<select id="findCustomerByName" parameterType="String"
                   resultType="com.itheima.po.Customer">
               select * from t_customer where username like '%${value}%'
       </select>

2.在测试类MybatisTest中,添加测试方法findCustomerByNameTest()。

/**

     * 根据用户名称来模糊查询用户信息列表

     */

    @Test

    public void findCustomerByNameTest() throws Exception{  

        // 1、读取配置文件

        String resource = "mybatis-config.xml";

        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 2、根据配置文件构建SqlSessionFactory

        SqlSessionFactory sqlSessionFactory = 

    new SqlSessionFactoryBuilder().build(inputStream);

        // 3、通过SqlSessionFactory创建SqlSession

        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 4、SqlSession执行映射文件中定义的SQL,并返回映射结果

        List<Customer> customers = sqlSession.selectList("com.itheima.mapper"

                    + ".CustomerMapper.findCustomerByName", "j");

        for (Customer customer : customers) {

            //打印输出结果集

            System.out.println(customer);

        }

        // 5、关闭SqlSession

        sqlSession.close();

    }


4-3-3-案例总结

4-4-添加客户

1.添加操作是通过<insert>元素来实现的。例如,向数据库中的t_customer表中插入一条数据可以通过如下配置来实现。

<insert id="addCustomer"  parameterType="com.itheima.po.Customer">
        insert into t_customer(username,jobs,phone)
        values(#{username},#{jobs},#{phone})
</insert>

2.在测试类MybatisTest中,添加测试方法addCustomerTest()。

@Test

    public void addCustomerTest() throws Exception{     

        // 1、读取配置文件

        String resource = "mybatis-config.xml";

        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 2、根据配置文件构建SqlSessionFactory

        SqlSessionFactory sqlSessionFactory = 

                new SqlSessionFactoryBuilder().build(inputStream);

        // 3、通过SqlSessionFactory创建SqlSession

        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 4、SqlSession执行添加操作

        // 4.1创建Customer对象,并向对象中添加数据

        Customer customer = new Customer();

        customer.setUsername("rose");

        customer.setJobs("student");

        customer.setPhone("13333533092");

        // 4.2执行SqlSession的插入方法,返回的是SQL语句影响的行数

        int rows = sqlSession.insert("com.itheima.mapper"

                    + ".CustomerMapper.addCustomer", customer);

        // 4.3通过返回结果判断插入操作是否执行成功

        if(rows > 0){

            System.out.println("您成功插入了"+rows+"条数据!");

        }else{

            System.out.println("执行插入操作失败!!!");

        }

        // 4.4提交事务

        sqlSession.commit();

        // 5、关闭SqlSession

        sqlSession.close();

    }


4-5-更新客户

1.更新操作在映射文件中是通过配置<update>元素来实现的。

<update id="updateCustomer" parameterType="com.itheima.po.Customer">
       update t_customer set
       username=#{username},jobs=#{jobs},phone=#{phone}
       where id=#{id}
</update>


2.  在测试类MybatisTest中,添加测试方法updateCustomerTest(),
将id为4的用户职业修改为programmer,电话修改为13311111111。

@Test

    public void updateCustomerTest() throws Exception{      

        // 1、读取配置文件

        String resource = "mybatis-config.xml";

        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 2、根据配置文件构建SqlSessionFactory

        SqlSessionFactory sqlSessionFactory = 

                new SqlSessionFactoryBuilder().build(inputStream);

        // 3、通过SqlSessionFactory创建SqlSession

        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 4、SqlSession执行更新操作

        // 4.1创建Customer对象,对对象中的数据进行模拟更新

        Customer customer = new Customer();

        customer.setId(4);

        customer.setUsername("rose");

        customer.setJobs("programmer");

        customer.setPhone("13311111111");

        // 4.2执行SqlSession的更新方法,返回的是SQL语句影响的行数

        int rows = sqlSession.update("com.itheima.mapper"

                + ".CustomerMapper.updateCustomer", customer);

        // 4.3通过返回结果判断更新操作是否执行成功

        if(rows > 0){

            System.out.println("您成功修改了"+rows+"条数据!");

        }else{

            System.out.println("执行修改操作失败!!!");

        }

        // 4.4提交事务

        sqlSession.commit();

        // 5、关闭SqlSession

        sqlSession.close();

    }


4-6- 删除客户

1. 删除操作在映射文件中是通过配置<delete>元素来实现的。

<delete id="deleteCustomer" parameterType="Integer">
       delete from t_customer where id=#{id}
</delete>


2. 在测试类MybatisTest中,添加测试方法deleteCustomerTest(),该方法用于将id为4的客户信息删除。

@Test

    public void deleteCustomerTest() throws Exception{      

        // 1、读取配置文件

        String resource = "mybatis-config.xml";

        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 2、根据配置文件构建SqlSessionFactory

        SqlSessionFactory sqlSessionFactory = 

                new SqlSessionFactoryBuilder().build(inputStream);

        // 3、通过SqlSessionFactory创建SqlSession

        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 4、SqlSession执行删除操作

        // 4.1执行SqlSession的删除方法,返回的是SQL语句影响的行数

        int rows = sqlSession.delete("com.itheima.mapper"

                + ".CustomerMapper.deleteCustomer", 4);

        // 4.2通过返回结果判断删除操作是否执行成功

        if(rows > 0){

            System.out.println("您成功删除了"+rows+"条数据!");

        }else{

            System.out.println("执行删除操作失败!!!");

        }

        // 4.3提交事务

        sqlSession.commit();

        // 5、关闭SqlSession

        sqlSession.close();

    }

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值