Mybatis初识

Mybatis初识

mybatis是一个支持普通sql查询,训处过程及高级映射的持久层框架,几乎消除了所偶的JDBC代码和参数的手动设置以及对结果集的检索,使用简单的XMl或注解进行配置和原始的映射

使用log4j输出日志信息

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

新建com.po包,创建Customer类

package com.po;

public class Customer {
   private Integer id;
   private String username;
   private String jobs;
   private String phone;

   public Integer getId() {
       return id;
   }

   public void setId(Integer id) {
       this.id = id;
   }

   public String getUsername() {
       return username;
   }

   public void setUsername(String username) {
       this.username = username;
   }

   public String getJobs() {
       return jobs;
   }

   public void setJobs(String jobs) {
       this.jobs = jobs;
   }

   public String getPhone() {
       return phone;
   }

   public void setPhone(String phone) {
       this.phone = phone;
   }

   @Override
   public String toString() {
       return "Customer{" +
               "id=" + id +
               ", username='" + username + '\'' +
               ", jobs='" + jobs + '\'' +
               ", phone='" + phone + '\'' +
               '}';
   }
}

创建com.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.mapper.CustomerMapper">
    <!--根据客户编号获取客户信息-->
    <select id="findCustomerById" parameterType="Integer" resultType="com.po.Customer">
        select * from t_customer where id=#{id}
    </select>
     <!--根据客户名称获取客户信息-->
    <select id="findCustomerByName" parameterType="String" resultType="com.po.Customer">
        select * from t_customer where username like concat('%',#{value},'%')
    </select>
     <!--插入信息-->
    <insert id="addCustomer" parameterType="com.po.Customer">
        insert into t_customer(username,jobs,phone)
        values(#{username},#{jobs},#{phone})
    </insert>
     <!--更新客户信息-->
    <update id="updateCustomer" parameterType="com.po.Customer">
        update t_customer set
        username=#{username},jobs=#{jobs},phone=#{phone}
        where username=#{username}
    </update>
     <!--根据客户编号删除客户信息-->
    <delete id="deleteCustomer" parameterType="Integer">
        delete from t_customer where id=#{id}
    </delete>
</mapper>

在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>
    <!--1.配置环境 ,默认的环境id为mysql-->
    <environments default="mysql">
        <!--1.2.配置id为mysql的数据库环境 -->
        <environment id="mysql">
            <!-- 使用JDBC的事务管理 -->
            <transactionManager type="JDBC" />
            <!--数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url"
                          value="jdbc:mysql://localhost:3306/mybatis" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/mapper/CustomerMapper.xml" />
    </mappers>
</configuration>

创建com.test包,编写每个测试类方法

package com.test;
import java.io.InputStream;
import java.util.List;

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 com.po.Customer;
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.mapper"+".CustomerMapper.findCustomerById",2);
        System.out.println(customer.toString());
        sqlSession.close();
    }
    @Test
    public void findCustomerByNameTest() throws Exception{
        String resource="mybatis-config.xml";
        InputStream inputStream=Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        List<Customer> customers=sqlSession.selectList("com.mapper"+".CustomerMapper.findCustomerByName","r");
        for(Customer customer:customers){
            System.out.println(customer);
        }
        sqlSession.close();
    }
    @Test
    public void addCustomerTest() throws Exception{
        String resource ="mybatis-config.xml";
        InputStream inputStream=Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        Customer customer=new Customer();
        customer.setUsername("rose");
        customer.setJobs("student");
        customer.setPhone("13333533092");
        int rows=sqlSession.insert("com.mapper"+".CustomerMapper.addCustomer",customer);
        if(rows>0){
            System.out.println("您成功插入"+rows+"条数据");
        }else{
            System.out.println("执行插入操作失败!!!");
        }
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void updateCustomerTest() throws Exception{
        String resource="mybatis-config.xml";
        InputStream inputStream=Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        Customer customer=new Customer();
        customer.setId(4);
        customer.setUsername("rose");
        customer.setJobs("programmer");
        customer.setPhone("1331111111");
        int rows=sqlSession.update("com.mapper"+".CustomerMapper.updateCustomer",customer);
        if(rows>0){
            System.out.println("您成功修改了"+rows+"条数据");
        }else{
            System.out.println("执行修改操作失败!!!");
        }
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void deleteCustomerTest() throws Exception{
        String resources="mybatis-config.xml";
        InputStream inputStream=Resources.getResourceAsStream(resources);
        SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        int rows=sqlSession.delete("com.mapper"+".CustomerMapper.deleteCustomer",4);
        if(rows>0){
            System.out.println("你成功删除了"+rows+"条数据");
        }else{
            System.out.println("执行删除操作失败!!!");
        }
        sqlSession.commit();
        sqlSession.close();
    }
}

遇到的问题

在这次学习过程中遇到的问题如下

一,错误提示java.lang.NoClassDefFoundError:org/hamcrest/SelfDescribing

在这里插入图片描述

解决方案

该错误是由于junit测试中缺少hamcrest-core.jar文件所致,添加即可解决问题

二、查询和删除操作失败

在这里插入图片描述

解决方案

先打开数据库,如图所示
在这里插入图片描述
我们发现没有id值为4的数据,因此会出现如下问题,所以我们可以添加一个id=4的数据或者改为按照用户名查询即可,只要符合SQL语法,想怎么该就怎么改。

三、控制台无法输出SQL语句

如上图所使
这种情况绝对是log4j文件编辑错误,不用想其他问题

四、插入数据提示成功后数据库中无相关信息

这中情况一般是由于事务未提交造成的,检查相关代码中是否有事务提交代码段(sqlSession.commit())

写在最后

Mybatis的操作大致可以分为如下几个步骤

1.读取配置文件
2.根据配置文件构建SqlSessionFactory
3.通过SqlSessionFactory创建SqlSession
4.使用SqlSession对象操作数据库
5.关闭Sqlsession

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值